cedarling 0.0.41

The Cedarling: a high-performance local authorization service powered by the Rust Cedar Engine.
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
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
// This software is available under the Apache-2.0 license.
// See https://www.apache.org/licenses/LICENSE-2.0.txt for full text.
//
// Copyright (c) 2024, Gluu, Inc.

//! Cedar entity parsing and validation.
//!
//! This module provides functionality to parse and validate Cedar entity files in JSON format,
//! ensuring they conform to Cedar's entity specification with proper UIDs, attributes, and
//! parent relationships.

use super::errors::{CedarEntityErrorType, PolicyStoreError};
use super::log_entry::PolicyStoreLogEntry;
use crate::log::Logger;
use crate::log::interface::LogWriter;
use cedar_policy::{Entities, Entity, EntityId, EntityTypeName, EntityUid, Schema};
use serde::{Deserialize, Serialize};
use serde_json::Value as JsonValue;
use std::collections::{HashMap, HashSet};
use std::str::FromStr;

/// A parsed Cedar entity with metadata.
///
/// Contains the Cedar entity and metadata about the source file.
#[derive(Debug, Clone)]
pub(super) struct ParsedEntity {
    /// The Cedar entity
    pub entity: Entity,
    /// The entity's UID
    pub uid: EntityUid,
    /// Source filename
    pub filename: String,
    /// Raw entity content (JSON)
    pub content: String,
}

/// Raw entity JSON structure as expected by Cedar.
///
/// This matches Cedar's JSON entity format with uid, attrs, and parents fields.
#[derive(Debug, Clone, Serialize, Deserialize)]
struct RawEntityJson {
    /// Entity unique identifier
    pub uid: EntityUidJson,
    /// Entity attributes as a map of attribute names to values (optional)
    #[serde(default)]
    pub attrs: HashMap<String, JsonValue>,
    /// Parent entity UIDs for hierarchy (optional)
    #[serde(default)]
    pub parents: Vec<EntityUidJson>,
}

/// Entity UID in JSON format.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Hash)]
struct EntityUidJson {
    /// Entity type (e.g., "`Jans::User`")
    #[serde(rename = "type")]
    pub entity_type: String,
    /// Entity ID
    pub id: String,
}

/// Wrapper for multiple entities that can be in array or object format.
///
/// This supports both formats commonly used in Cedar entity files:
/// - Array: `[{entity1}, {entity2}]`
/// - Object: `{"id1": {entity1}, "id2": {entity2}}`
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(untagged)]
enum RawEntitiesWrapper {
    /// Array of entity objects
    Array(Vec<JsonValue>),
    /// Object mapping IDs to entity objects
    Object(HashMap<String, JsonValue>),
}

/// Entity parser for loading and validating Cedar entities.
pub(crate) struct EntityParser;

impl EntityParser {
    /// Parse a single Cedar entity from JSON value.
    ///
    /// Validates the entity structure, parses the UID, attributes, and parent relationships.
    /// Optionally validates entity attributes against a schema.
    ///
    /// # Errors
    /// Returns `PolicyStoreError` if:
    /// - JSON parsing fails
    /// - Entity structure is invalid
    /// - UID format is invalid
    /// - Parent UID format is invalid
    /// - Schema validation fails (if schema provided)
    fn parse_entity(
        entity_json: &JsonValue,
        filename: &str,
        schema: Option<&Schema>,
    ) -> Result<ParsedEntity, PolicyStoreError> {
        // Parse the JSON structure
        let raw_entity: RawEntityJson =
            serde_json::from_value(entity_json.clone()).map_err(|e| {
                PolicyStoreError::JsonParsing {
                    file: filename.to_string(),
                    source: e,
                }
            })?;

        // Parse the entity UID
        let uid = Self::parse_entity_uid(&raw_entity.uid, filename)?;

        // Validate parent UIDs format (don't collect, just validate)
        for parent_uid in &raw_entity.parents {
            Self::parse_entity_uid(parent_uid, filename)?;
        }

        // Use Cedar's Entity::from_json_value to parse the entity with attributes
        // This properly handles attribute conversion to RestrictedExpression
        let entity_json_for_cedar = serde_json::json!({
            "uid": {
                "type": raw_entity.uid.entity_type,
                "id": raw_entity.uid.id
            },
            "attrs": raw_entity.attrs,
            "parents": raw_entity.parents
        });

        // Parse with optional schema validation using Entity::from_json_value
        let entity = Entity::from_json_value(entity_json_for_cedar, schema).map_err(|e| {
            PolicyStoreError::CedarEntityError {
                file: filename.to_string(),
                err: CedarEntityErrorType::JsonParseError(format!(
                    "Failed to parse entity{}: {}",
                    if schema.is_some() {
                        " (schema validation failed)"
                    } else {
                        ""
                    },
                    e
                )),
            }
        })?;

        Ok(ParsedEntity {
            entity,
            uid,
            filename: filename.to_string(),
            content: serde_json::to_string(entity_json).unwrap_or_default(),
        })
    }

    /// Parse multiple entities from a JSON array or object.
    ///
    /// Supports both array format: `[{entity1}, {entity2}]`
    /// And object format: `{"entity_id1": {entity1}, "entity_id2": {entity2}}`
    pub(super) fn parse_entities(
        content: &str,
        filename: &str,
        schema: Option<&Schema>,
    ) -> Result<Vec<ParsedEntity>, PolicyStoreError> {
        let json_value: JsonValue =
            serde_json::from_str(content).map_err(|e| PolicyStoreError::JsonParsing {
                file: filename.to_string(),
                source: e,
            })?;

        // Use untagged enum to handle both array and object formats
        let wrapper: RawEntitiesWrapper =
            serde_json::from_value(json_value).map_err(|e| PolicyStoreError::CedarEntityError {
                file: filename.to_string(),
                err: CedarEntityErrorType::JsonParseError(format!(
                    "Entity file must contain a JSON array or object: {e}"
                )),
            })?;

        let entity_values: Vec<&JsonValue> = match &wrapper {
            RawEntitiesWrapper::Array(arr) => arr.iter().collect(),
            RawEntitiesWrapper::Object(obj) => obj.values().collect(),
        };

        let mut parsed_entities = Vec::with_capacity(entity_values.len());
        for entity_json in entity_values {
            let parsed = Self::parse_entity(entity_json, filename, schema)?;
            parsed_entities.push(parsed);
        }

        Ok(parsed_entities)
    }

    /// Parse an [`EntityUid`] from JSON format.
    fn parse_entity_uid(
        uid_json: &EntityUidJson,
        filename: &str,
    ) -> Result<EntityUid, PolicyStoreError> {
        // Parse the entity type name
        let entity_type = EntityTypeName::from_str(&uid_json.entity_type).map_err(|e| {
            PolicyStoreError::CedarEntityError {
                file: filename.to_string(),
                err: CedarEntityErrorType::InvalidTypeName(
                    uid_json.entity_type.clone(),
                    e.to_string(),
                ),
            }
        })?;

        // Parse the entity ID
        let entity_id =
            EntityId::from_str(&uid_json.id).map_err(|e| PolicyStoreError::CedarEntityError {
                file: filename.to_string(),
                err: CedarEntityErrorType::InvalidEntityId(format!(
                    "Invalid entity ID '{}': {}",
                    uid_json.id, e
                )),
            })?;

        Ok(EntityUid::from_type_name_and_id(entity_type, entity_id))
    }

    /// Detect and handle duplicate entity UIDs.
    ///
    /// Returns a map of entity UIDs to their parsed entities.
    /// If duplicates are found, logs warnings and uses the latest entity (last-write-wins).
    /// This approach ensures Cedarling can start even with duplicate entities,
    /// avoiding crashes of dependent applications while still alerting developers.
    pub(super) fn detect_duplicates(
        entities: Vec<ParsedEntity>,
        logger: Option<&Logger>,
    ) -> HashMap<EntityUid, ParsedEntity> {
        let mut entity_map: HashMap<EntityUid, ParsedEntity> =
            HashMap::with_capacity(entities.len());

        for entity in entities {
            if let Some(existing) = entity_map.get(&entity.uid) {
                // Warn about duplicate but continue - use the latest entity
                logger.log_any(PolicyStoreLogEntry::warn(format!(
                    "Duplicate entity UID '{}' found in files '{}' and '{}'. Using the latter.",
                    entity.uid, existing.filename, entity.filename
                )));
            }
            // Always insert - latest entity wins (last-write-wins semantics)
            entity_map.insert(entity.uid.clone(), entity);
        }

        entity_map
    }

    /// Create a Cedar Entities store from parsed entities.
    ///
    /// Validates that all entities are compatible and can be used together.
    pub(super) fn create_entities_store(
        entities: Vec<ParsedEntity>,
    ) -> Result<Entities, PolicyStoreError> {
        let entity_list: Vec<Entity> = entities.into_iter().map(|p| p.entity).collect();

        Entities::from_entities(entity_list, None).map_err(|e| PolicyStoreError::CedarEntityError {
            file: "entity_store".to_string(),
            err: CedarEntityErrorType::EntityStoreCreation(e.to_string()),
        })
    }

    /// Validate entity hierarchy.
    ///
    /// Ensures that all parent references point to entities that exist in the collection.
    pub(super) fn validate_hierarchy(entities: &[ParsedEntity]) -> Result<(), Vec<String>> {
        let entity_uids: HashSet<&EntityUid> = entities.iter().map(|e| &e.uid).collect();
        let mut errors: Vec<String> = Vec::new();

        for parsed_entity in entities {
            // Get parents directly from the entity using into_inner()
            // into_inner() returns (uid, attrs, parents)
            let parents = &parsed_entity.entity.clone().into_inner().2;

            for parent_uid in parents {
                if !entity_uids.contains(parent_uid) {
                    errors.push(format!(
                        "Entity '{}' in file '{}' references non-existent parent '{}'",
                        parsed_entity.uid, parsed_entity.filename, parent_uid
                    ));
                }
            }
        }

        if errors.is_empty() {
            Ok(())
        } else {
            Err(errors)
        }
    }
}

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

    #[test]
    fn test_parse_simple_entity() {
        let content = serde_json::json!({
            "uid": {
                "type": "User",
                "id": "alice"
            },
            "attrs": {
                "name": "Alice",
                "age": 30
            },
            "parents": []
        });

        let result = EntityParser::parse_entity(&content, "user1.json", None);
        assert!(
            result.is_ok(),
            "Should parse simple entity: {:?}",
            result.err()
        );

        let parsed = result.unwrap();
        assert_eq!(parsed.filename, "user1.json");
        assert_eq!(parsed.uid.to_string(), "User::\"alice\"");
    }

    #[test]
    fn test_parse_entity_with_parents() {
        let content = serde_json::json!({
            "uid": {
                "type": "User",
                "id": "bob"
            },
            "attrs": {
                "name": "Bob"
            },
            "parents": [
                {
                    "type": "Role",
                    "id": "admin"
                },
                {
                    "type": "Role",
                    "id": "developer"
                }
            ]
        });

        let parsed = EntityParser::parse_entity(&content, "user2.json", None)
            .expect("Should parse entity with parents");
        // Verify parents using into_inner()
        let parents = &parsed.entity.clone().into_inner().2;
        assert_eq!(parents.len(), 2, "Should have 2 parents");
    }

    #[test]
    fn test_parse_entity_with_namespace() {
        let content = serde_json::json!({
            "uid": {
                "type": "Jans::User",
                "id": "user123"
            },
            "attrs": {
                "email": "user@example.com"
            },
            "parents": []
        });

        let parsed = EntityParser::parse_entity(&content, "jans_user.json", None)
            .expect("Should parse entity with namespace");
        assert_eq!(parsed.uid.to_string(), "Jans::User::\"user123\"");
    }

    #[test]
    fn test_parse_entity_empty_attrs() {
        let content = serde_json::json!({
            "uid": {
                "type": "Resource",
                "id": "res1"
            },
            "attrs": {},
            "parents": []
        });

        EntityParser::parse_entity(&content, "resource.json", None)
            .expect("Should parse entity with empty attrs");
    }

    #[test]
    fn test_parse_entity_invalid_json() {
        let content = serde_json::json!("not an object");

        let result = EntityParser::parse_entity(&content, "invalid.json", None);
        let err = result.expect_err("Should fail on invalid JSON");

        assert!(
            matches!(&err, PolicyStoreError::JsonParsing { file, .. } if file == "invalid.json"),
            "Expected JsonParsing error, got: {err:?}"
        );
    }

    #[test]
    fn test_parse_entity_invalid_type() {
        let content = serde_json::json!({
            "uid": {
                "type": "Invalid Type Name!",
                "id": "test"
            },
            "attrs": {},
            "parents": []
        });

        let result = EntityParser::parse_entity(&content, "invalid_type.json", None);
        let err = result.expect_err("Should fail on invalid entity type");
        assert!(
            matches!(&err, PolicyStoreError::CedarEntityError { .. }),
            "Expected CedarEntityError for invalid entity type, got: {err:?}"
        );
    }

    #[test]
    fn test_parse_entities_array() {
        let content = r#"[
            {
                "uid": {"type": "User", "id": "user1"},
                "attrs": {"name": "User One"},
                "parents": []
            },
            {
                "uid": {"type": "User", "id": "user2"},
                "attrs": {"name": "User Two"},
                "parents": []
            }
        ]"#;

        let parsed = EntityParser::parse_entities(content, "users.json", None)
            .expect("Should parse entity array");
        assert_eq!(parsed.len(), 2, "Should have 2 entities");
    }

    #[test]
    fn test_parse_entities_object() {
        let content = r#"{
            "user1": {
                "uid": {"type": "User", "id": "user1"},
                "attrs": {},
                "parents": []
            },
            "user2": {
                "uid": {"type": "User", "id": "user2"},
                "attrs": {},
                "parents": []
            }
        }"#;

        let parsed = EntityParser::parse_entities(content, "users.json", None)
            .expect("Should parse entity object");
        assert_eq!(parsed.len(), 2, "Should have 2 entities");
    }

    #[test]
    fn test_detect_duplicates_none() {
        let entities = vec![
            ParsedEntity {
                entity: Entity::new(
                    "User::\"alice\"".parse().unwrap(),
                    HashMap::new(),
                    HashSet::new(),
                )
                .unwrap(),
                uid: "User::\"alice\"".parse().unwrap(),
                filename: "user1.json".to_string(),
                content: String::new(),
            },
            ParsedEntity {
                entity: Entity::new(
                    "User::\"bob\"".parse().unwrap(),
                    HashMap::new(),
                    HashSet::new(),
                )
                .unwrap(),
                uid: "User::\"bob\"".parse().unwrap(),
                filename: "user2.json".to_string(),
                content: String::new(),
            },
        ];

        // No logger needed for this test - duplicates are handled gracefully
        let map = EntityParser::detect_duplicates(entities, None);
        assert_eq!(map.len(), 2, "Should have 2 unique entities");
    }

    #[test]
    fn test_detect_duplicates_uses_latest() {
        // Create two entities with the same UID but different filenames
        // The second (latest) one should be used
        let entities = vec![
            ParsedEntity {
                entity: Entity::new(
                    "User::\"alice\"".parse().unwrap(),
                    HashMap::new(),
                    HashSet::new(),
                )
                .unwrap(),
                uid: "User::\"alice\"".parse().unwrap(),
                filename: "user1.json".to_string(),
                content: String::new(),
            },
            ParsedEntity {
                entity: Entity::new(
                    "User::\"alice\"".parse().unwrap(),
                    HashMap::new(),
                    HashSet::new(),
                )
                .unwrap(),
                uid: "User::\"alice\"".parse().unwrap(),
                filename: "user2.json".to_string(),
                content: String::new(),
            },
        ];

        // Duplicates should be handled gracefully - no error, just warning (no logger here)
        let map = EntityParser::detect_duplicates(entities, None);

        // Should have 1 unique entity (the duplicate was handled)
        assert_eq!(
            map.len(),
            1,
            "Should have 1 unique entity after handling duplicate"
        );

        // The latest entity (from user2.json) should be used
        let alice = map.get(&"User::\"alice\"".parse().unwrap()).unwrap();
        assert_eq!(
            alice.filename, "user2.json",
            "Should use the latest entity (last-write-wins)"
        );
    }

    #[test]
    fn test_validate_hierarchy_valid() {
        // Create parent entity
        let parent = ParsedEntity {
            entity: Entity::new(
                "Role::\"admin\"".parse().unwrap(),
                HashMap::new(),
                HashSet::new(),
            )
            .unwrap(),
            uid: "Role::\"admin\"".parse().unwrap(),
            filename: "role.json".to_string(),
            content: String::new(),
        };

        // Create child entity with parent reference
        let mut parent_set = HashSet::new();
        parent_set.insert("Role::\"admin\"".parse().unwrap());

        let child = ParsedEntity {
            entity: Entity::new(
                "User::\"alice\"".parse().unwrap(),
                HashMap::new(),
                parent_set,
            )
            .unwrap(),
            uid: "User::\"alice\"".parse().unwrap(),
            filename: "user.json".to_string(),
            content: String::new(),
        };

        let entities = vec![parent, child];
        EntityParser::validate_hierarchy(&entities).expect("Hierarchy should be valid");
    }

    #[test]
    fn test_validate_hierarchy_missing_parent() {
        // Create child entity with non-existent parent reference
        let mut parent_set = HashSet::new();
        parent_set.insert("Role::\"admin\"".parse().unwrap());

        let child = ParsedEntity {
            entity: Entity::new(
                "User::\"alice\"".parse().unwrap(),
                HashMap::new(),
                parent_set,
            )
            .unwrap(),
            uid: "User::\"alice\"".parse().unwrap(),
            filename: "user.json".to_string(),
            content: String::new(),
        };

        let entities = vec![child];
        let result = EntityParser::validate_hierarchy(&entities);
        let errors = result.expect_err("Should detect missing parent");

        assert_eq!(errors.len(), 1, "Should have 1 hierarchy error");
        assert!(
            errors[0].contains("Role::\"admin\""),
            "Error should reference missing parent Role::admin, got: {}",
            errors[0]
        );
    }

    #[test]
    fn test_create_entities_store() {
        let entities = vec![
            ParsedEntity {
                entity: Entity::new(
                    "User::\"alice\"".parse().unwrap(),
                    HashMap::new(),
                    HashSet::new(),
                )
                .unwrap(),
                uid: "User::\"alice\"".parse().unwrap(),
                filename: "user1.json".to_string(),
                content: String::new(),
            },
            ParsedEntity {
                entity: Entity::new(
                    "User::\"bob\"".parse().unwrap(),
                    HashMap::new(),
                    HashSet::new(),
                )
                .unwrap(),
                uid: "User::\"bob\"".parse().unwrap(),
                filename: "user2.json".to_string(),
                content: String::new(),
            },
        ];

        let store =
            EntityParser::create_entities_store(entities).expect("Should create entity store");
        assert_eq!(store.iter().count(), 2, "Store should have 2 entities");
    }

    #[test]
    fn test_parse_entity_with_schema_validation() {
        use cedar_policy::{Schema, SchemaFragment};
        use std::str::FromStr;

        // Create a schema that defines User entity type
        let schema_src = r"
            entity User = {
                name: String,
                age: Long
            };
        ";

        let fragment = SchemaFragment::from_str(schema_src).expect("Should parse schema");
        let schema = Schema::from_schema_fragments([fragment]).expect("Should create schema");

        // Valid entity matching schema
        let valid_content = serde_json::json!({
            "uid": {
                "type": "User",
                "id": "alice"
            },
            "attrs": {
                "name": "Alice",
                "age": 30
            },
            "parents": []
        });

        let result = EntityParser::parse_entity(&valid_content, "user.json", Some(&schema));
        assert!(
            result.is_ok(),
            "Should parse entity with valid schema: {:?}",
            result.err()
        );
    }
}