1use std::collections::{HashMap, HashSet};
2
3use cedrus_cedar::{Entity, EntityUid, entity::EntityAttr};
4use serde::{Deserialize, Serialize};
5use utoipa::ToSchema;
6use uuid::Uuid;
7
8use crate::{CedrusRole, Role};
9
10pub const PROJECT_ENTITY_TYPE: &str = "Project";
11pub const APIKEY_ENTITY_TYPE: &str = "ApiKey";
12pub const GROUP_ENTITY_TYPE: &str = "Group";
13pub const USER_ENTITY_TYPE: &str = "User";
14
15pub const PARENT_UID: &str = "Application::Cedrus";
16
17const ATTR_ENABLED: &str = "enabled";
18const ATTR_OWNER: &str = "owner";
19const TAG_NAME: &str = "name";
20
21fn default_true() -> bool {
22 true
23}
24
25use crate::project::is::OpenIdConnectTokenSelection;
26
27pub mod is {
28 use super::*;
29
30 #[derive(Debug, Default, Clone, Serialize, Deserialize, PartialEq, ToSchema)]
31 #[schema(as = identitysource::CognitoGroupConfiguration)]
32 #[serde(rename_all = "camelCase")]
33 pub struct CognitoGroupConfiguration {
34 pub group_entity_type: String,
35 }
36
37 #[derive(Debug, Default, Clone, Serialize, Deserialize, PartialEq, ToSchema)]
38 #[schema(as = identitysource::CognitoUserPoolConfiguration)]
39 #[serde(rename_all = "camelCase")]
40 pub struct CognitoUserPoolConfiguration {
41 pub user_pool_arn: String,
42 pub client_ids: Vec<String>,
43 pub group_configuration: Option<CognitoGroupConfiguration>,
44 }
45
46 impl CognitoUserPoolConfiguration {
47 pub fn iss(&self) -> String {
48 let parts: Vec<&str> = self.user_pool_arn.split(':').collect();
49 let region = parts.get(3).expect("Invalid user pool ARN");
50 let user_pool_id = self
51 .user_pool_arn
52 .split('/')
53 .next_back()
54 .expect("Invalid user pool ARN")
55 .to_string();
56
57 format!("https://cognito-idp.{region}.amazonaws.com/{user_pool_id}")
58 }
59
60 pub fn url_keys(&self) -> String {
61 let parts: Vec<&str> = self.user_pool_arn.split(':').collect();
62 let region = parts.get(3).expect("Invalid user pool ARN");
63 let user_pool_id = self
64 .user_pool_arn
65 .split('/')
66 .next_back()
67 .expect("Invalid user pool ARN")
68 .to_string();
69
70 format!(
71 "https://cognito-idp.{region}.amazonaws.com/{user_pool_id}/.well-known/jwks.json"
72 )
73 }
74
75 pub fn prefix(&self) -> String {
76 self.user_pool_arn
77 .split('/')
78 .next_back()
79 .expect("Invalid user pool ARN")
80 .to_string()
81 }
82 }
83
84 #[derive(Debug, Default, Clone, Serialize, Deserialize, PartialEq, ToSchema)]
85 #[schema(as = identitysource::OpenIdConnectAccessTokenConfiguration)]
86 #[serde(rename_all = "camelCase", default)]
87 pub struct OpenIdConnectAccessTokenConfiguration {
88 #[serde(skip_serializing_if = "Vec::is_empty")]
89 pub audiences: Vec<String>,
90 #[serde(skip_serializing_if = "Option::is_none")]
91 pub principal_id_claim: Option<String>,
92 }
93
94 #[derive(Debug, Default, Clone, Serialize, Deserialize, PartialEq, ToSchema)]
95 #[schema(as = identitysource::OpenIdConnectIdentityTokenConfiguration)]
96 #[serde(rename_all = "camelCase", default)]
97 pub struct OpenIdConnectIdentityTokenConfiguration {
98 #[serde(skip_serializing_if = "Vec::is_empty")]
99 pub client_ids: Vec<String>,
100 #[serde(skip_serializing_if = "Option::is_none")]
101 pub principal_id_claim: Option<String>,
102 }
103
104 #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, ToSchema)]
105 #[schema(as = identitysource::OpenIdConnectTokenSelection)]
106 #[serde(rename_all = "camelCase")]
107 pub enum OpenIdConnectTokenSelection {
108 AccessTokenOnly(OpenIdConnectAccessTokenConfiguration),
109 IdentityTokenOnly(OpenIdConnectIdentityTokenConfiguration),
110 }
111
112 impl Default for OpenIdConnectTokenSelection {
113 fn default() -> Self {
114 OpenIdConnectTokenSelection::AccessTokenOnly(
115 OpenIdConnectAccessTokenConfiguration::default(),
116 )
117 }
118 }
119
120 #[derive(Debug, Default, Clone, Serialize, Deserialize, PartialEq, ToSchema)]
121 #[schema(as = identitysource::OpenIdConnectGroupConfiguration)]
122 #[serde(rename_all = "camelCase")]
123 pub struct OpenIdConnectGroupConfiguration {
124 pub group_claim: String,
125 pub group_entity_type: String,
126 }
127
128 #[derive(Debug, Default, Clone, Serialize, Deserialize, PartialEq, ToSchema)]
129 #[schema(as = identitysource::OpenIdConnectConfiguration)]
130 #[serde(rename_all = "camelCase")]
131 pub struct OpenIdConnectConfiguration {
132 pub issuer: String,
133 pub token_selection: OpenIdConnectTokenSelection,
134 #[serde(skip_serializing_if = "Option::is_none")]
135 pub entity_id_prefix: Option<String>,
136 #[serde(skip_serializing_if = "Option::is_none")]
137 pub group_configuration: Option<OpenIdConnectGroupConfiguration>,
138 }
139
140 #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, ToSchema)]
141 #[schema(as = identitysource::Configuration)]
142 #[serde(rename_all = "camelCase")]
143 pub enum Configuration {
144 CognitoUserPoolConfiguration(CognitoUserPoolConfiguration),
145 OpenIdConnectConfiguration(OpenIdConnectConfiguration),
146 }
147
148 impl Default for Configuration {
149 fn default() -> Self {
150 Configuration::CognitoUserPoolConfiguration(CognitoUserPoolConfiguration::default())
151 }
152 }
153}
154
155#[derive(Debug, Default, Clone, Serialize, Deserialize, PartialEq, ToSchema)]
156#[serde(rename_all = "camelCase")]
157pub struct IdentitySource {
158 pub principal_entity_type: String,
159 pub configuration: is::Configuration,
160}
161
162impl IdentitySource {
163 pub fn prefix(&self) -> String {
164 match &self.configuration {
165 is::Configuration::CognitoUserPoolConfiguration(config) => config
166 .user_pool_arn
167 .split('/')
168 .next_back()
169 .expect("Invalid user pool ARN")
170 .to_string(),
171 is::Configuration::OpenIdConnectConfiguration(config) => {
172 match config.entity_id_prefix {
173 Some(ref val) => val.clone(),
174 None => config.issuer.replace("http://", "").replace("https://", ""),
175 }
176 }
177 }
178 }
179
180 pub fn id_claim(&self) -> String {
181 match &self.configuration {
182 is::Configuration::CognitoUserPoolConfiguration(_) => "sub".to_string(),
183 is::Configuration::OpenIdConnectConfiguration(conf) => match &conf.token_selection {
184 OpenIdConnectTokenSelection::AccessTokenOnly(token) => {
185 match &token.principal_id_claim {
186 Some(val) => val.clone(),
187 None => "sub".to_string(),
188 }
189 }
190 OpenIdConnectTokenSelection::IdentityTokenOnly(token) => {
191 match &token.principal_id_claim {
192 Some(val) => val.clone(),
193 None => "sub".to_string(),
194 }
195 }
196 },
197 }
198 }
199
200 pub fn group_claim(&self) -> Option<String> {
201 match &self.configuration {
202 is::Configuration::CognitoUserPoolConfiguration(_) => {
203 Some("cognito:groups".to_string())
204 }
205 is::Configuration::OpenIdConnectConfiguration(conf) => conf
206 .group_configuration
207 .as_ref()
208 .map(|group| group.group_claim.clone()),
209 }
210 }
211
212 pub fn group_entity_type(&self) -> Option<String> {
213 match &self.configuration {
214 is::Configuration::CognitoUserPoolConfiguration(conf) => conf
215 .group_configuration
216 .as_ref()
217 .map(|group| group.group_entity_type.clone()),
218 is::Configuration::OpenIdConnectConfiguration(conf) => conf
219 .group_configuration
220 .as_ref()
221 .map(|group| group.group_entity_type.clone()),
222 }
223 }
224}
225
226#[derive(Debug, Default, Clone, Serialize, Deserialize, ToSchema, PartialEq, Eq)]
227#[serde(rename_all = "camelCase", default)]
228pub struct ApiKey {
229 pub id: Uuid,
230 pub key: String,
231 pub name: String,
232 #[serde(default = "default_true")]
233 pub enabled: bool,
234 pub project_id: Uuid,
235 pub owner: EntityUid,
236 pub role: Role,
237 pub expires_at: Option<chrono::DateTime<chrono::Utc>>,
238 pub created_at: chrono::DateTime<chrono::Utc>,
239 pub updated_at: chrono::DateTime<chrono::Utc>,
240}
241
242impl ApiKey {
243 pub fn new(
244 id: Uuid,
245 key: String,
246 name: String,
247 project_id: Uuid,
248 owner: EntityUid,
249 role: Role,
250 expires_at: Option<chrono::DateTime<chrono::Utc>>,
251 ) -> Self {
252 let now = chrono::Utc::now();
253
254 Self {
255 id,
256 key,
257 name,
258 enabled: true,
259 project_id,
260 owner,
261 role,
262 expires_at,
263 created_at: now,
264 updated_at: now,
265 }
266 }
267
268 pub fn is_expired_at(&self, now: chrono::DateTime<chrono::Utc>) -> bool {
270 self.expires_at.is_some_and(|expires| now >= expires)
271 }
272
273 pub fn is_expired(&self) -> bool {
275 self.is_expired_at(chrono::Utc::now())
276 }
277
278 pub fn entity_uid(&self) -> EntityUid {
280 EntityUid::new(
281 APIKEY_ENTITY_TYPE.to_string(),
282 format!("{}|{}", self.project_id, self.id),
283 )
284 }
285
286 pub fn entity(&self) -> Entity {
288 let uid = self.entity_uid();
289 let attrs = HashMap::from([(ATTR_ENABLED.to_string(), EntityAttr::Boolean(self.enabled))]);
290 let parents = HashSet::from([EntityUid::from(PARENT_UID)]);
291 let tags = HashMap::from([(TAG_NAME.to_string(), EntityAttr::String(self.name.clone()))]);
292
293 Entity::new_with_tags(uid, attrs, parents, tags)
294 }
295
296 pub fn policy_id(&self) -> String {
298 format!("apikey_{}_{}", self.project_id, self.id)
299 }
300
301 pub fn template_id(&self) -> Option<&'static str> {
303 match &self.role {
304 Role::Preset(base) => Some(match base {
305 CedrusRole::Admin => "AdminRole",
306 CedrusRole::Editor => "EditorRole",
307 CedrusRole::Viewer => "ViewerRole",
308 }),
309 Role::Custom(_) => None,
310 }
311 }
312}
313
314#[derive(Debug, Default, Clone, Serialize, Deserialize, ToSchema, PartialEq, Eq)]
315#[serde(rename_all = "camelCase", default)]
316pub struct Project {
317 pub id: Uuid,
318 #[serde(skip_serializing_if = "String::is_empty")]
319 pub name: String,
320
321 #[serde(default = "default_true")]
322 pub enabled: bool,
323
324 pub owner: EntityUid,
325
326 pub created_at: chrono::DateTime<chrono::Utc>,
327 pub updated_at: chrono::DateTime<chrono::Utc>,
328}
329
330impl Project {
331 pub fn new(id: Uuid, name: String, owner: EntityUid) -> Self {
332 let now = chrono::Utc::now();
333
334 Self {
335 id,
336 name,
337 enabled: true,
338 owner,
339 created_at: now,
340 updated_at: now,
341 }
342 }
343
344 pub fn entity_uid(id: Uuid) -> EntityUid {
345 EntityUid::new(PROJECT_ENTITY_TYPE.to_string(), id.to_string())
346 }
347
348 pub fn entity(&self) -> Entity {
349 let uid = EntityUid::new(PROJECT_ENTITY_TYPE.to_string(), self.id.to_string());
350 let attrs = HashMap::from([
351 (ATTR_ENABLED.to_string(), EntityAttr::Boolean(true)),
352 (
353 ATTR_OWNER.to_string(),
354 EntityAttr::EntityUid(self.owner.clone()),
355 ),
356 ]);
357 let parents = HashSet::from([EntityUid::from(PARENT_UID)]);
358 let tags = HashMap::from([(TAG_NAME.to_string(), EntityAttr::String(self.name.clone()))]);
359
360 Entity::new_with_tags(uid, attrs, parents, tags)
361 }
362}
363
364#[cfg(test)]
365mod tests {
366 use super::*;
367
368 #[test]
369 fn test_api_key_expiration() {
370 let now = chrono::Utc::now();
371 let past = now - chrono::Duration::hours(1);
372 let future = now + chrono::Duration::hours(1);
373
374 let owner = EntityUid::new("User".to_string(), "user-123".to_string());
375 let key_no_expiry = ApiKey::new(
376 Uuid::nil(),
377 "key-1".to_string(),
378 "No Expiry".to_string(),
379 Uuid::nil(),
380 owner.clone(),
381 Role::default(),
382 None,
383 );
384 assert!(!key_no_expiry.is_expired_at(now));
385
386 let key_expired = ApiKey::new(
387 Uuid::nil(),
388 "key-2".to_string(),
389 "Expired".to_string(),
390 Uuid::nil(),
391 owner.clone(),
392 Role::default(),
393 Some(past),
394 );
395 assert!(key_expired.is_expired_at(now));
396
397 let key_valid = ApiKey::new(
398 Uuid::nil(),
399 "key-3".to_string(),
400 "Valid".to_string(),
401 Uuid::nil(),
402 owner,
403 Role::default(),
404 Some(future),
405 );
406 assert!(!key_valid.is_expired_at(now));
407 }
408
409 #[test]
410 fn test_api_key_serde_backward_compatibility() {
411 let json_without_expires_at = r#"{
412 "id": "00000000-0000-0000-0000-000000000000",
413 "key": "test_key",
414 "name": "Legacy Key",
415 "projectId": "00000000-0000-0000-0000-000000000000",
416 "owner": { "type": "User", "id": "owner" },
417 "role": { "type": "Preset", "value": "Viewer" },
418 "createdAt": "2026-01-01T00:00:00Z",
419 "updatedAt": "2026-01-01T00:00:00Z"
420 }"#;
421
422 let api_key: ApiKey = serde_json::from_str(json_without_expires_at).unwrap();
423 assert_eq!(api_key.expires_at, None);
424 assert!(api_key.enabled);
425 assert!(!api_key.is_expired());
426 }
427
428 #[test]
429 fn test_api_key_entity() {
430 let owner = EntityUid::new("User".to_string(), "owner".to_string());
431 let mut api_key = ApiKey::new(
432 Uuid::nil(),
433 "key".to_string(),
434 "My Key".to_string(),
435 Uuid::nil(),
436 owner,
437 Role::default(),
438 None,
439 );
440 let entity = api_key.entity();
441 assert_eq!(
442 entity.attrs().get("enabled"),
443 Some(&EntityAttr::Boolean(true))
444 );
445
446 api_key.enabled = false;
447 let entity_disabled = api_key.entity();
448 assert_eq!(
449 entity_disabled.attrs().get("enabled"),
450 Some(&EntityAttr::Boolean(false))
451 );
452 }
453
454 #[test]
455 fn test_project_name_validation() {
456 let owner = EntityUid::new("User".to_string(), "owner".to_string());
457 let project_empty = Project::new(Uuid::nil(), "".to_string(), owner.clone());
458 assert!(project_empty.name.trim().is_empty());
459
460 let project_whitespace = Project::new(Uuid::nil(), " ".to_string(), owner.clone());
461 assert!(project_whitespace.name.trim().is_empty());
462
463 let project_valid = Project::new(Uuid::nil(), "My Project".to_string(), owner);
464 assert!(!project_valid.name.trim().is_empty());
465 }
466}