cedarling 0.0.65

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
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
// 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.

use base64::prelude::*;
use cedar_policy::Entity;
use cedar_policy::EntityId;
use cedar_policy::EntityTypeName;
use cedar_policy::EntityUid;
use cedar_policy::ExpressionConstructionError;
use cedar_policy::RestrictedExpression;
use serde_json::Value;
use std::collections::HashMap;
use std::collections::HashSet;
use std::str::FromStr;
use std::string::FromUtf8Error;
use std::sync::Arc;

use crate::common::default_entities_limits::{DefaultEntitiesLimits, DefaultEntitiesLimitsError};
use crate::entity_builder::BuildEntityError;
use crate::entity_builder::build_cedar_entity;
use crate::entity_builder::value_to_expr;

/// Dangerous patterns that should not appear in entity IDs for security reasons
const DANGEROUS_PATTERNS: [&str; 6] = [
    "<script",
    "javascript:",
    "data:",
    "vbscript:",
    "onload=",
    "onerror=",
];

#[derive(Debug, Default, Clone, PartialEq)]
pub(crate) struct DefaultEntities {
    pub(crate) inner: Arc<HashMap<EntityUid, Entity>>,
}

impl DefaultEntities {
    /// Get entity by [`EntityUid`]
    pub(crate) fn get(&self, key: &EntityUid) -> Option<&Entity> {
        self.inner.get(key)
    }

    /// Returns the number of elements in the map.
    pub(crate) fn len(&self) -> usize {
        self.inner.len()
    }
}

/// Structure that holds parsed default entities along with non-fatal parsing issues.
/// Warnings collected during parsing are exposed via the `warns` method.
///
/// # JSON Serialization
/// This structure is deserialized from JSON with the following format:
/// - `None` or empty map: Returns empty default entities
/// - Map of entity IDs to entity data:
///   - Base64-encoded JSON string: Decoded and parsed as entity
///   - JSON object: Parsed directly as entity
///
/// Entity data supports two formats:
/// - Cedar format: {"uid": {"type": "...", "id": "..."}, "attrs": {...}, "parents": [...]}
/// - Legacy format: {"`entity_type"`: "...", "`entity_id"`: "...", ...attributes...}
///
/// # JSON Map Example
/// ```json
/// {
///   "user123": {
///     "uid": {
///       "type": "User",
///       "id": "user123"
///     },
///     "attrs": {
///       "name": "John Doe",
///       "age": 30
///     },
///     "parents": [
///       {
///         "type": "Group",
///         "id": "admin"
///       }
///     ]
///   },
///   "user456": "eyJ1aWQiOnsidHlwZSI6IlVzZXIiLCJpZCI6InVzZXI0NTYifSwiYXR0cnMiOnsibmFtZSI6IkpvaG4gRG9lIn19"
/// }
/// ```
#[derive(Debug, Default, Clone, PartialEq)]
pub(crate) struct DefaultEntitiesWithWarns {
    inner: DefaultEntities,
    warns: Vec<DefaultEntityWarning>,
}

impl DefaultEntitiesWithWarns {
    fn new(entities: HashMap<EntityUid, Entity>, warns: Vec<DefaultEntityWarning>) -> Self {
        Self {
            inner: DefaultEntities {
                inner: Arc::new(entities),
            },
            warns,
        }
    }

    /// Get default entities
    pub(crate) fn entities(&self) -> &DefaultEntities {
        &self.inner
    }

    /// Gets warnings generated during the parsing phase.
    pub(crate) fn warns(&self) -> &[DefaultEntityWarning] {
        &self.warns
    }
}

/// Parse default entities from raw data, returning entities and warnings
pub(super) fn parse_default_entities_with_warns(
    raw_data: Option<HashMap<String, Value>>,
) -> Result<DefaultEntitiesWithWarns, ParseDefaultEntityError> {
    let limits = DefaultEntitiesLimits::default();

    if let Some(raw_data) = raw_data {
        let mut default_entities = HashMap::new();
        let mut warns = Vec::new();

        for (n, (entry_id, raw_value)) in raw_data.into_iter().enumerate() {
            // `n` starts with zero, so we add 1
            let entity_count = n + 1;

            // Validate against limits (using default limits for deserialization)
            // Note: Configuration limits will be applied later when the policy store is initialized

            // check size of base64 string
            limits
                .validate_default_entity(&entry_id, &raw_value)
                .map_err(|err| {
                    ParseEntityErrorKind::LimitsValidation(err).with_entry_id(entry_id.clone())
                })?;
            // check size of HashMap using explicit counter
            limits
                .validate_entities_count(entity_count)
                .map_err(|err| {
                    ParseEntityErrorKind::LimitsValidation(err).with_entry_id(entry_id.clone())
                })?;

            let entity = match &raw_value {
                Value::String(b64_string) => {
                    parse_base64_single_entity(&mut warns, &entry_id, b64_string)?
                },
                Value::Object(_) => parse_single_entity(&mut warns, &entry_id, &raw_value)?,
                _ => {
                    return Err(ParseEntityErrorKind::IsNotJsonObject.with_entry_id(entry_id));
                },
            };

            default_entities.insert(entity.uid().clone(), entity);
        }

        Ok(DefaultEntitiesWithWarns::new(default_entities, warns))
    } else {
        // If none, return default value
        Ok(DefaultEntitiesWithWarns::default())
    }
}

#[derive(Debug, thiserror::Error)]
#[error("failed to parse default entity, id: \"{entry_id}\" error: {error}")]
pub(super) struct ParseDefaultEntityError {
    pub entry_id: String,
    pub error: Box<ParseEntityErrorKind>,
}

#[derive(Debug, thiserror::Error)]
pub(super) enum ParseEntityErrorKind {
    #[error("unable to decode base64 string: {0}")]
    Base64Decode(#[from] base64::DecodeError),
    #[error("unable to decode base64 string as utf8: {0}")]
    UnicodeDecode(#[from] FromUtf8Error),
    #[error("base64 decoded value is not valid json: {0}")]
    Base64DecodedIsNotJson(#[from] serde_json::Error),
    #[error("entity ID cannot be empty or whitespace-only")]
    EntityIdIsEmpty,
    #[error("entity ID contains potentially dangerous content")]
    EntityIdIsDangerous,
    #[error("entity data must be JSON object")]
    IsNotJsonObject,
    #[error("entity has invalid 'uid.type' field, expect string")]
    InvalidUidTypeField,
    #[error("entity has invalid 'entity_type' field, expect string")]
    InvalidEntityTypeField,
    #[error("entity must have either 'uid.type' or 'entity_type' (legacy format) field")]
    HaveNoUidOrEntityTypeField,
    #[error(transparent)]
    BuildEntity(BuildEntityError),
    #[error("Failed to convert attribute '{attr}' to cedar expr: {errs:?}")]
    ParseEntityAttribute {
        attr: String,
        errs: Vec<ExpressionConstructionError>,
    },
    #[error("default entities limits validation failed: {0}")]
    LimitsValidation(#[from] DefaultEntitiesLimitsError),
}

#[derive(Debug, thiserror::Error, Clone, PartialEq, Eq)]
pub(crate) enum DefaultEntityWarning {
    #[error(
        "Could not parse parent UID '{parent_uid_str}' for default entity '{entry_id}': {error}"
    )]
    InvalidParentUid {
        entry_id: String,
        parent_uid_str: String,
        error: String,
    },
    #[error(
        "In default entity '{entry_id}' each parent entry must be an object with 'type' and 'id'; skipping value: {value}"
    )]
    NonObjectParentEntry { entry_id: String, value: String },
}

impl ParseEntityErrorKind {
    fn with_entry_id(self, entry_id: String) -> ParseDefaultEntityError {
        ParseDefaultEntityError {
            entry_id,
            error: Box::new(self),
        }
    }
}

/// Decode base64 string into UTF-8 JSON and call [`parse_single_entity`]
fn parse_base64_single_entity(
    warns: &mut Vec<DefaultEntityWarning>,
    entry_id: &str,
    b64: &str,
) -> Result<Entity, ParseDefaultEntityError> {
    let buf = BASE64_STANDARD.decode(b64).map_err(|err| {
        ParseEntityErrorKind::Base64Decode(err).with_entry_id(entry_id.to_owned())
    })?;

    let json_str = String::from_utf8(buf).map_err(|err| {
        ParseEntityErrorKind::UnicodeDecode(err).with_entry_id(entry_id.to_owned())
    })?;

    let entity_data: serde_json::Value = serde_json::from_str(&json_str).map_err(|err| {
        ParseEntityErrorKind::Base64DecodedIsNotJson(err).with_entry_id(entry_id.to_owned())
    })?;

    let entity = parse_single_entity(warns, entry_id, &entity_data)?;
    Ok(entity)
}

/// Parse single entity, return entity and error (in critical case),
/// But not critical case will populate `warn` vector with log message
fn parse_single_entity(
    warns: &mut Vec<DefaultEntityWarning>,
    entry_id: &str,
    entity_data: &Value,
) -> Result<Entity, ParseDefaultEntityError> {
    validate_entry_id(entry_id)?;

    let Value::Object(entity_obj) = entity_data else {
        return Err(ParseEntityErrorKind::IsNotJsonObject.with_entry_id(entry_id.to_owned()));
    };

    let parse_result = if entity_obj.contains_key("uid") {
        // New Cedar entity format: {"uid": {"type": "...", "id": "..."}, "attrs": {}, "parents": [...]}
        parse_cedar_format(warns, entry_id, entity_data)?
    } else if entity_obj.contains_key("entity_type") {
        // Old format with entity_type field
        parse_legacy_format(warns, entry_id, entity_data)?
    } else {
        return Err(
            ParseEntityErrorKind::HaveNoUidOrEntityTypeField.with_entry_id(entry_id.to_owned())
        );
    };

    let entity = build_cedar_entity(
        parse_result.entity_type,
        parse_result.entity_id,
        parse_result.cedar_attrs,
        parse_result.parents,
    )
    .map_err(|err| ParseEntityErrorKind::BuildEntity(err).with_entry_id(entry_id.to_owned()))?;
    Ok(entity)
}

/// Validate entry ID for security and format requirements
fn validate_entry_id(entry_id: &str) -> Result<(), ParseDefaultEntityError> {
    if entry_id.trim().is_empty() {
        return Err(ParseEntityErrorKind::EntityIdIsEmpty.with_entry_id(entry_id.to_owned()));
    }

    let entry_id_lower = entry_id.to_lowercase();
    for pattern in &DANGEROUS_PATTERNS {
        if entry_id_lower.contains(pattern) {
            return Err(
                ParseEntityErrorKind::EntityIdIsDangerous.with_entry_id(entry_id.to_owned())
            );
        }
    }

    Ok(())
}

/// Result structure for entity parsing with named parameters
struct EntityParseResultData<'a> {
    pub entity_type: &'a str,
    pub entity_id: &'a str,
    pub cedar_attrs: HashMap<String, RestrictedExpression>,
    pub parents: HashSet<EntityUid>,
}

/// Parse entity in the new Cedar format with "uid" field
fn parse_cedar_format<'a>(
    warns: &mut Vec<DefaultEntityWarning>,
    entry_id: &'a str,
    entity_data: &'a Value,
) -> Result<EntityParseResultData<'a>, ParseDefaultEntityError> {
    let Value::Object(entity_obj) = entity_data else {
        return Err(ParseEntityErrorKind::IsNotJsonObject.with_entry_id(entry_id.to_owned()));
    };

    // get uid and type
    let entity_type = entity_obj
        .get("uid")
        .and_then(|v| v.as_object())
        .and_then(|v| v.get("type"))
        .and_then(|v| v.as_str())
        .ok_or_else(|| {
            ParseEntityErrorKind::InvalidUidTypeField.with_entry_id(entry_id.to_owned())
        })?;

    // Get the entity ID from uid.id if present
    let entity_id_from_uid = entity_obj
        .get("uid")
        .and_then(|v| v.as_object())
        .and_then(|v| v.get("id"))
        .and_then(|v| v.as_str())
      // Fall back to the HashMap key if uid.id is not specified
        .unwrap_or(entry_id);

    // Parse attributes from attrs field
    let empty_map = serde_json::Map::new();
    let attrs_obj = entity_obj
        .get("attrs")
        .and_then(|v| v.as_object())
        .unwrap_or(&empty_map);

    let cedar_attrs = parse_entity_attrs(attrs_obj.iter(), entry_id)?;

    // Parse parents from parents field
    let empty_vec: Vec<Value> = Vec::new();
    let parents_array = entity_obj
        .get("parents")
        .and_then(|v| v.as_array())
        .unwrap_or(&empty_vec);

    let mut parents_set = HashSet::new();
    for parent in parents_array {
        if let Value::Object(parent_obj) = parent
            && let (Some(parent_entity_type), Some(id_v)) = (
                parent_obj.get("type").and_then(|v| v.as_str()),
                parent_obj.get("id").and_then(|v| v.as_str()),
            )
        {
            let entity_id = EntityId::from_str(id_v).unwrap_or_else(|e| match e {});
            match EntityTypeName::from_str(parent_entity_type) {
                Ok(type_name) => {
                    let parent_uid = EntityUid::from_type_name_and_id(type_name, entity_id);
                    parents_set.insert(parent_uid);
                },
                Err(e) => {
                    // log warn that we could not parse uid
                    warns.push(DefaultEntityWarning::InvalidParentUid {
                        entry_id: entry_id.to_string(),
                        parent_uid_str: format!("{parent_entity_type}::\"{id_v}\""),
                        error: e.to_string(),
                    });
                },
            }
        } else {
            // log warn that we skip value because it is not object
            warns.push(DefaultEntityWarning::NonObjectParentEntry {
                entry_id: entry_id.to_string(),
                value: parent.to_string(),
            });
        }
    }

    Ok(EntityParseResultData {
        entity_type,
        entity_id: entity_id_from_uid,
        cedar_attrs,
        parents: parents_set,
    })
}

/// Parse entity in the legacy format with "`entity_type`" field
fn parse_legacy_format<'a>(
    _warns: &mut Vec<DefaultEntityWarning>,
    entry_id: &'a str,
    entity_data: &'a Value,
) -> Result<EntityParseResultData<'a>, ParseDefaultEntityError> {
    let Value::Object(entity_obj) = entity_data else {
        return Err(ParseEntityErrorKind::IsNotJsonObject.with_entry_id(entry_id.to_owned()));
    };

    let entity_type = entity_obj
        .get("entity_type")
        .and_then(|v| v.as_str())
        .ok_or_else(|| {
            ParseEntityErrorKind::InvalidEntityTypeField.with_entry_id(entry_id.to_owned())
        })?;

    let entity_id_from_uid = entity_obj
        .get("entity_id")
        .and_then(|v| v.as_str())
        .unwrap_or(entry_id);

    // Convert JSON attributes to Cedar expressions
    let cedar_attrs = parse_entity_attrs(
        entity_obj
            .iter()
            .filter(|(key, _)| key != &"entity_type" && key != &"entity_id"),
        entry_id,
    )?;

    Ok(EntityParseResultData {
        entity_type,
        entity_id: entity_id_from_uid,
        cedar_attrs,
        parents: HashSet::new(),
    })
}

/// Helper function to parse entity attributes from a key-value iterator
fn parse_entity_attrs<'a>(
    attrs_iter: impl Iterator<Item = (&'a String, &'a Value)>,
    entry_id: &str,
) -> Result<HashMap<String, RestrictedExpression>, ParseDefaultEntityError> {
    let mut cedar_attrs = HashMap::new();
    for (key, value) in attrs_iter {
        match value_to_expr::value_to_expr(value) {
            Ok(Some(expr)) => {
                cedar_attrs.insert(key.clone(), expr);
            },
            Ok(None) => {},
            Err(errors) => {
                return Err(ParseEntityErrorKind::ParseEntityAttribute {
                    attr: key.to_owned(),
                    errs: errors,
                }
                .with_entry_id(entry_id.to_owned()));
            },
        }
    }
    Ok(cedar_attrs)
}

#[cfg(test)]
mod test {
    use super::DANGEROUS_PATTERNS;
    use super::{DefaultEntityWarning, ParseEntityErrorKind, parse_default_entities_with_warns};
    use base64::Engine;
    use cedar_policy::EntityUid;
    use serde_json::{Value, json};
    use std::collections::HashMap;
    use std::str::FromStr;
    use test_utils::assert_eq;

    #[test]
    fn can_parse_default_entities() {
        // Test the parse_default_entities function directly
        // We don't need the schema for this test since we're not validating the entities

        // Create test default entities
        let default_entities_data = json!({
                "1694c954f8d9".to_string(): json!({
                    "entity_id": "1694c954f8d9",
                    "entity_type": "Jans::DefaultEntity",
                    "o": "Acme Dolphins Division",
                    "org_id": "100129"
                }),
        });

        let raw_data: HashMap<String, Value> =
            serde_json::from_value(default_entities_data).unwrap();
        let parsed_entities = parse_default_entities_with_warns(Some(raw_data))
            .expect("should parse default entities");
        let entities_hashmap = &parsed_entities.entities();

        assert_eq!(entities_hashmap.len(), 1, "should have 1 default entity");

        // Verify the entity
        let entity = entities_hashmap
            .get(&EntityUid::from_str("Jans::DefaultEntity::\"1694c954f8d9\"").unwrap())
            .expect("should have entity");
        assert_eq!(entity.uid().type_name().to_string(), "Jans::DefaultEntity");
        assert_eq!(entity.uid().id().as_ref() as &str, "1694c954f8d9");
    }

    #[test]
    fn test_parse_error_missing_uid() {
        // Test entity missing uid field
        let entity_data = json!({
            "attrs": {
                "attribute": "value"
            }
        });

        let default_entities_data = json!({"test123".to_string(): entity_data});
        let raw_data: HashMap<String, Value> =
            serde_json::from_value(default_entities_data).unwrap();

        let err = parse_default_entities_with_warns(Some(raw_data))
            .expect_err("Expected error for entity missing uid field");
        assert_eq!(err.entry_id, "test123", "Expected entry_id to be 'test123'");
        assert!(
            matches!(*err.error, ParseEntityErrorKind::HaveNoUidOrEntityTypeField),
            "Expected error to be HaveNoUidOrEntityTypeField"
        );
    }

    #[test]
    fn test_parse_error_invalid_uid_structure() {
        // Test entity with uid that is not an object
        let entity_data = json!({
            "uid": "not-an-object",
            "attrs": {}
        });

        let default_entities_data = json!({"test123".to_string(): entity_data});
        let raw_data: HashMap<String, Value> =
            serde_json::from_value(default_entities_data).unwrap();

        let err = parse_default_entities_with_warns(Some(raw_data))
            .expect_err("Expected error when uid is not an object");
        assert_eq!(err.entry_id, "test123", "Expected entry_id to be 'test123'");
        assert!(
            matches!(*err.error, ParseEntityErrorKind::InvalidUidTypeField),
            "Expected error to be InvalidUidTypeField"
        );

        // Test entity with uid missing type field
        let entity_data_no_type = json!({
            "uid": {
                "id": "test"
            },
            "attrs": {}
        });

        let default_entities_data = json!({"test456".to_string(): entity_data_no_type});
        let raw_data: HashMap<String, Value> =
            serde_json::from_value(default_entities_data).unwrap();
        let err = parse_default_entities_with_warns(Some(raw_data))
            .expect_err("Expected error when uid.type is missing");
        assert_eq!(err.entry_id, "test456", "Expected entry_id to be 'test456'");
        assert!(
            matches!(*err.error, ParseEntityErrorKind::InvalidUidTypeField),
            "Expected error to be InvalidUidTypeField"
        );
    }

    #[test]
    fn test_parse_entity_with_empty_attrs_and_parents() {
        // Test entity with empty attrs and empty parents
        let entity_data = json!({
            "uid": {
                "type": "Test::EmptyTest",
                "id": "test789"
            },
            "attrs": {},
            "parents": []
        });

        let default_entities_data = json!({"test789".to_string(): entity_data});
        let raw_data: HashMap<String, Value> =
            serde_json::from_value(default_entities_data).unwrap();
        let parsed_entities = parse_default_entities_with_warns(Some(raw_data))
            .expect("should parse with empty attrs and parents");
        let entities = parsed_entities.entities();

        let uid = EntityUid::from_str("Test::EmptyTest::\"test789\"").unwrap();
        let entity = entities.get(&uid).expect("should have entity");
        assert_eq!(
            entity.uid().type_name().to_string(),
            "Test::EmptyTest",
            "Entity type should have namespace prefix"
        );
        let entity_json = entity.to_json_value().expect("should convert to JSON");
        let attrs = entity_json.get("attrs").expect("should have attrs");
        assert_eq!(
            attrs.as_object().unwrap().len(),
            0,
            "Entity should have empty attrs"
        );
    }

    #[test]
    fn test_entry_id_validation_empty_and_whitespace() {
        // Test empty entry ID
        let entity_data = json!({
            "uid": {
                "type": "Test::Type",
                "id": "test"
            },
            "attrs": {}
        });

        let default_entities_data = json!({String::new(): entity_data});
        let raw_data: HashMap<String, Value> =
            serde_json::from_value(default_entities_data).unwrap();
        let err = parse_default_entities_with_warns(Some(raw_data))
            .expect_err("Expected error for empty entry ID");
        assert_eq!(err.entry_id, "", "Expected entry_id to be empty");
        assert!(
            matches!(*err.error, ParseEntityErrorKind::EntityIdIsEmpty),
            "Expected error to be EntityIdIsEmpty"
        );

        // Test whitespace-only entry ID
        let default_entities_data_whitespace = json!({"   ".to_string(): entity_data});
        let raw_data: HashMap<String, Value> =
            serde_json::from_value(default_entities_data_whitespace).unwrap();
        let err = parse_default_entities_with_warns(Some(raw_data))
            .expect_err("Expected error for whitespace-only entry ID");
        assert_eq!(
            err.entry_id, "   ",
            "Expected entry_id to be whitespace-only"
        );
        assert!(
            matches!(*err.error, ParseEntityErrorKind::EntityIdIsEmpty),
            "Expected error to be EntityIdIsEmpty"
        );
    }

    #[test]
    fn test_entry_id_validation_dangerous_patterns() {
        let entity_data = json!({
            "uid": {
                "type": "Test::Type",
                "id": "test"
            },
            "attrs": {}
        });

        for pattern in DANGEROUS_PATTERNS {
            let dangerous_id = format!("prefix{pattern}suffix");
            let default_entities_data = json!({dangerous_id.clone(): entity_data.clone()});
            let raw_data: HashMap<String, Value> =
                serde_json::from_value(default_entities_data).unwrap();
            let err = parse_default_entities_with_warns(Some(raw_data)).expect_err(&format!(
                "Should return error for dangerous pattern: {pattern}"
            ));
            assert_eq!(
                err.entry_id, dangerous_id,
                "Expected entry_id to match dangerous pattern"
            );
            assert!(
                matches!(*err.error, ParseEntityErrorKind::EntityIdIsDangerous),
                "Expected error to be EntityIdIsDangerous"
            );
        }
    }

    #[test]
    fn test_valid_entry_ids() {
        // Test various valid entry IDs
        let valid_ids = [
            "normal_id",
            "id_with_underscore",
            "id-with-dash",
            "id123",
            "ID_IN_UPPERCASE",
            "id.with.dots",
        ];

        for valid_id in valid_ids {
            let entity_data = json!({
                "uid": {
                    "type": "Test::Type",
                    "id": valid_id
                },
                "attrs": {}
            });

            let default_entities_data = json!({valid_id.to_string(): entity_data.clone()});
            let raw_data: HashMap<String, Value> =
                serde_json::from_value(default_entities_data).unwrap();
            let parsed_entities = parse_default_entities_with_warns(Some(raw_data))
                .unwrap_or_else(|_| panic!("Should parse valid entry ID: {valid_id}"));

            assert_eq!(parsed_entities.entities().len(), 1, "Should have 1 entity");
        }
    }

    #[test]
    fn test_base64_parsing_valid() {
        // Create a valid entity JSON and encode it as base64
        let entity_json = json!({
            "uid": {
                "type": "Test::Base64Type",
                "id": "base64_test"
            },
            "attrs": {
                "test_attr": "test_value"
            }
        });

        let entity_json_str = entity_json.to_string();
        let b64_encoded = base64::prelude::BASE64_STANDARD.encode(entity_json_str);

        let default_entities_data = json!({
            "base64_entity".to_string(): b64_encoded
        });

        let raw_data: HashMap<String, Value> =
            serde_json::from_value(default_entities_data).unwrap();
        let parsed_entities = parse_default_entities_with_warns(Some(raw_data))
            .expect("Should parse valid base64 entity");

        assert_eq!(parsed_entities.entities().len(), 1, "Should have 1 entity");

        let uid = EntityUid::from_str("Test::Base64Type::\"base64_test\"").unwrap();
        let entity = parsed_entities
            .entities()
            .get(&uid)
            .expect("should have entity");
        assert_eq!(entity.uid().type_name().to_string(), "Test::Base64Type");
    }

    #[test]
    fn test_base64_parsing_invalid_base64() {
        // Test invalid base64 string
        let invalid_b64 = "not-valid-base64==";

        let default_entities_data = json!({
            "invalid_base64_entity".to_string(): invalid_b64
        });

        let raw_data: HashMap<String, Value> =
            serde_json::from_value(default_entities_data).unwrap();
        let err = parse_default_entities_with_warns(Some(raw_data))
            .expect_err("Expected error for invalid base64");
        assert_eq!(
            err.entry_id, "invalid_base64_entity",
            "Expected entry_id to be 'invalid_base64_entity'"
        );
        assert!(
            matches!(*err.error, ParseEntityErrorKind::Base64Decode(_)),
            "Expected error to be Base64Decode"
        );
    }

    #[test]
    fn test_base64_parsing_invalid_json_after_decode() {
        // Test base64 that decodes to invalid JSON
        let invalid_json = "not valid json";
        let b64_encoded = base64::prelude::BASE64_STANDARD.encode(invalid_json);

        let default_entities_data = json!({
            "invalid_json_entity".to_string(): b64_encoded
        });

        let raw_data: HashMap<String, Value> =
            serde_json::from_value(default_entities_data).unwrap();
        let err = parse_default_entities_with_warns(Some(raw_data))
            .expect_err("Expected error for invalid JSON after base64 decode");
        assert_eq!(
            err.entry_id, "invalid_json_entity",
            "Expected entry_id to be 'invalid_json_entity'"
        );
        assert!(
            matches!(*err.error, ParseEntityErrorKind::Base64DecodedIsNotJson(_)),
            "Expected error to be Base64DecodedIsNotJson"
        );
    }

    #[test]
    fn test_base64_parsing_non_utf8_content() {
        // Test base64 that decodes to non-UTF8 content
        let non_utf8_bytes = vec![0xFF, 0xFE, 0x00]; // Invalid UTF-8 sequence
        let b64_encoded = base64::prelude::BASE64_STANDARD.encode(non_utf8_bytes);

        let default_entities_data = json!({
            "non_utf8_entity".to_string(): b64_encoded
        });

        let raw_data: HashMap<String, Value> =
            serde_json::from_value(default_entities_data).unwrap();
        let err = parse_default_entities_with_warns(Some(raw_data))
            .expect_err("Expected error for non-UTF8 content after base64 decode");
        assert_eq!(
            err.entry_id, "non_utf8_entity",
            "Expected entry_id to be 'non_utf8_entity'"
        );
        assert!(
            matches!(*err.error, ParseEntityErrorKind::UnicodeDecode(_)),
            "Expected error to be UnicodeDecode"
        );
    }

    #[test]
    fn test_namespace_handling() {
        // Test entity with explicit namespace (already contains ::)
        let entity_with_namespace = json!({
            "uid": {
                "type": "Custom::Namespace::EntityType",
                "id": "test1"
            },
            "attrs": {}
        });

        // Test entity without namespace (should not get namespace prefix)
        let entity_without_namespace = json!({
            "uid": {
                "type": "SimpleType",
                "id": "test2"
            },
            "attrs": {}
        });

        let default_entities_data = json!({
            "test1".to_string(): entity_with_namespace,
            "test2".to_string(): entity_without_namespace
        });

        let raw_data: HashMap<String, Value> =
            serde_json::from_value(default_entities_data).unwrap();
        let parsed_entities = parse_default_entities_with_warns(Some(raw_data))
            .expect("Should parse entities with and without namespaces");

        assert_eq!(
            parsed_entities.entities().len(),
            2,
            "Should have 2 entities"
        );

        // Verify entity with explicit namespace
        let uid1 = EntityUid::from_str("Custom::Namespace::EntityType::\"test1\"").unwrap();
        let entity1 = parsed_entities
            .entities()
            .get(&uid1)
            .expect("should have entity1");
        assert_eq!(
            entity1.uid().type_name().to_string(),
            "Custom::Namespace::EntityType"
        );

        // Verify entity without namespace
        let uid2 = EntityUid::from_str("SimpleType::\"test2\"").unwrap();
        let entity2 = parsed_entities
            .entities()
            .get(&uid2)
            .expect("should have entity2");
        assert_eq!(entity2.uid().type_name().to_string(), "SimpleType");
    }

    #[test]
    fn test_legacy_format_parsing() {
        // Test legacy format with entity_type field
        let legacy_entity = json!({
            "entity_type": "Legacy::Type",
            "entity_id": "legacy_test",
            "custom_attr": "custom_value"
        });

        let default_entities_data = json!({
            "legacy_entity".to_string(): legacy_entity
        });

        let raw_data: HashMap<String, Value> =
            serde_json::from_value(default_entities_data).unwrap();
        let parsed_entities = parse_default_entities_with_warns(Some(raw_data))
            .expect("Should parse legacy format entity");

        assert_eq!(parsed_entities.entities().len(), 1, "Should have 1 entity");

        let uid = EntityUid::from_str("Legacy::Type::\"legacy_test\"").unwrap();
        let entity = parsed_entities
            .entities()
            .get(&uid)
            .expect("should have entity");
        assert_eq!(entity.uid().type_name().to_string(), "Legacy::Type");

        // Verify attributes are parsed correctly
        let entity_json = entity.to_json_value().expect("should convert to JSON");
        let attrs = entity_json.get("attrs").expect("should have attrs");
        let custom_attr = attrs.get("custom_attr").expect("should have custom_attr");
        assert_eq!(custom_attr.as_str().unwrap(), "custom_value");
    }

    #[test]
    fn test_parent_entity_parsing() {
        // Test entity with valid parent entities
        let entity_with_parents = json!({
            "uid": {
                "type": "Test::ChildType",
                "id": "child_entity"
            },
            "attrs": {},
            "parents": [
                {
                    "type": "Test::ParentType1",
                    "id": "parent1"
                },
                {
                    "type": "Test::ParentType2",
                    "id": "parent2"
                }
            ]
        });

        let default_entities_data = json!({
            "child_entity".to_string(): entity_with_parents
        });

        let raw_data: HashMap<String, Value> =
            serde_json::from_value(default_entities_data).unwrap();
        let parsed_entities = parse_default_entities_with_warns(Some(raw_data))
            .expect("Should parse entity with parents");

        assert_eq!(parsed_entities.entities().len(), 1, "Should have 1 entity");

        let uid = EntityUid::from_str("Test::ChildType::\"child_entity\"").unwrap();
        let entity = parsed_entities
            .entities()
            .get(&uid)
            .expect("should have entity");

        // Verify the entity was parsed successfully with parents
        // The parents are stored internally but we can't easily access them from the Entity
        // The main verification is that parsing succeeded with the parent data
        let _ = entity;
    }

    #[test]
    fn test_parent_entity_parsing_with_warnings() {
        // Test entity with invalid parent entries that should generate warnings
        let entity_with_invalid_parents = json!({
            "uid": {
                "type": "Test::Type",
                "id": "test_entity"
            },
            "attrs": {},
            "parents": [
                {
                    "type": "ValidParent",
                    "id": "valid"
                },
                {
                    "type": "InvalidParent",
                    "id": "invalid@uid"  // Invalid UID format
                },
                "not_an_object",  // Invalid parent format
                {
                    "missing_type": "parent",  // Missing type field
                    "id": "parent3"
                }
            ]
        });

        let default_entities_data = json!({
            "test_entity".to_string(): entity_with_invalid_parents
        });

        let raw_data: HashMap<String, Value> =
            serde_json::from_value(default_entities_data).unwrap();
        let parsed_entities = parse_default_entities_with_warns(Some(raw_data))
            .expect("Should parse entity with invalid parents (but generate warnings)");

        // Should still parse the entity successfully
        assert_eq!(parsed_entities.entities().len(), 1, "Should have 1 entity");

        // Should have warnings for invalid parents
        assert!(!parsed_entities.warns().is_empty(), "Should have warnings");

        // Verify the valid parent was parsed
        let uid = EntityUid::from_str("Test::Type::\"test_entity\"").unwrap();
        let _entity = parsed_entities
            .entities()
            .get(&uid)
            .expect("should have entity");

        // The entity was parsed successfully despite invalid parents
        // The warnings should indicate that some parents were skipped
    }

    #[test]
    fn test_attribute_parsing_various_types() {
        // Test entity with various attribute types
        let entity_with_attrs = json!({
            "uid": {
                "type": "Test::AttrType",
                "id": "attr_test"
            },
            "attrs": {
                "string_attr": "string_value",
                "number_attr": 42,
                "bool_attr": true,
                "array_attr": ["item1", "item2"],
                "object_attr": {"nested": "value"}
            }
        });

        let default_entities_data = json!({
            "attr_test".to_string(): entity_with_attrs
        });

        let raw_data: HashMap<String, Value> =
            serde_json::from_value(default_entities_data).unwrap();
        let parsed_entities = parse_default_entities_with_warns(Some(raw_data))
            .expect("Should parse entity with various attribute types");

        assert_eq!(parsed_entities.entities().len(), 1, "Should have 1 entity");

        let uid = EntityUid::from_str("Test::AttrType::\"attr_test\"").unwrap();
        let entity = parsed_entities
            .entities()
            .get(&uid)
            .expect("should have entity");

        // Verify attributes are present
        let entity_json = entity.to_json_value().expect("should convert to JSON");
        let attrs = entity_json.get("attrs").expect("should have attrs");
        let attrs_obj = attrs.as_object().expect("attrs should be object");

        assert_eq!(attrs_obj.len(), 5, "Should have 5 attributes");
        assert_eq!(
            attrs_obj.get("string_attr").unwrap().as_str().unwrap(),
            "string_value"
        );
        assert_eq!(attrs_obj.get("number_attr").unwrap().as_i64().unwrap(), 42);
        assert_eq!(attrs_obj.get("bool_attr").unwrap().as_bool().unwrap(), true);
    }

    #[test]
    fn test_entity_without_uid_id_falls_back_to_entry_id() {
        // Test entity where uid.id is not specified - should fall back to entry_id
        let entity_without_uid_id = json!({
            "uid": {
                "type": "Test::FallbackType"
                // No "id" field
            },
            "attrs": {}
        });

        let entry_id = "fallback_entry_id";
        let default_entities_data = json!({entry_id.to_string(): entity_without_uid_id});

        let raw_data: HashMap<String, Value> =
            serde_json::from_value(default_entities_data).unwrap();
        let parsed_entities = parse_default_entities_with_warns(Some(raw_data))
            .expect("Should parse entity with fallback ID");

        assert_eq!(parsed_entities.entities().len(), 1, "Should have 1 entity");

        // Entity UID should use the entry_id as fallback
        let uid = EntityUid::from_str("Test::FallbackType::\"fallback_entry_id\"").unwrap();
        let entity = parsed_entities
            .entities()
            .get(&uid)
            .expect("should have entity");
        assert_eq!(entity.uid().id().as_ref() as &str, "fallback_entry_id");
    }

    #[test]
    fn test_empty_default_entities() {
        // Test deserializing None/empty default entities
        let parsed_entities =
            parse_default_entities_with_warns(None).expect("Should parse empty default entities");

        assert_eq!(
            parsed_entities.entities().len(),
            0,
            "Should have 0 entities"
        );
        assert!(
            parsed_entities.warns().is_empty(),
            "Should have no warnings"
        );
    }

    #[test]
    fn test_invalid_value_type_error() {
        // Test entity with invalid value type (not object or base64 string)
        let default_entities_data = json!({
            "invalid_entity".to_string(): 12345  // Number instead of object/string
        });

        let raw_data: HashMap<String, Value> =
            serde_json::from_value(default_entities_data).unwrap();
        let err = parse_default_entities_with_warns(Some(raw_data))
            .expect_err("Expected error for invalid value type");
        assert_eq!(
            err.entry_id, "invalid_entity",
            "Expected entry_id to be 'invalid_entity'"
        );
        assert!(
            matches!(*err.error, ParseEntityErrorKind::IsNotJsonObject),
            "Expected error to be IsNotJsonObject"
        );
    }

    #[test]
    fn test_mixed_format_entities() {
        // Test parsing a mix of base64 and JSON object entities

        // Create a base64 encoded entity
        let base64_entity_json = json!({
            "uid": {
                "type": "Test::Base64Type",
                "id": "base64_entity"
            },
            "attrs": {
                "source": "base64"
            }
        });
        let base64_encoded =
            base64::prelude::BASE64_STANDARD.encode(base64_entity_json.to_string());

        // Create a regular JSON object entity
        let json_entity = json!({
            "uid": {
                "type": "Test::JsonType",
                "id": "json_entity"
            },
            "attrs": {
                "source": "json"
            }
        });

        let default_entities_data = json!({
            "base64_entity".to_string(): base64_encoded,
            "json_entity".to_string(): json_entity
        });

        let raw_data: HashMap<String, Value> =
            serde_json::from_value(default_entities_data).unwrap();
        let parsed_entities = parse_default_entities_with_warns(Some(raw_data))
            .expect("Should parse mixed format entities");

        assert_eq!(
            parsed_entities.entities().len(),
            2,
            "Should have 2 entities"
        );

        // Verify both entities were parsed correctly
        let base64_uid = EntityUid::from_str("Test::Base64Type::\"base64_entity\"").unwrap();
        let json_uid = EntityUid::from_str("Test::JsonType::\"json_entity\"").unwrap();

        assert!(
            parsed_entities.entities().get(&base64_uid).is_some(),
            "Should have base64 entity"
        );
        assert!(
            parsed_entities.entities().get(&json_uid).is_some(),
            "Should have json entity"
        );
    }

    #[test]
    fn test_warning_enum_invalid_parent_uid() {
        // Test that invalid parent UIDs generate proper warnings
        let entity_with_invalid_parent = json!({
            "uid": {
                "type": "Test::Type",
                "id": "test_entity"
            },
            "attrs": {},
            "parents": [
                {
                    "type": "InvalidParent",
                    "id": "invalid@uid"  // This should be valid, so let's test with a truly invalid format
                }
            ]
        });

        let default_entities_data = json!({
            "test_entity".to_string(): entity_with_invalid_parent
        });

        let raw_data: HashMap<String, Value> =
            serde_json::from_value(default_entities_data).unwrap();
        let parsed_entities = parse_default_entities_with_warns(Some(raw_data))
            .expect("Should parse entity with invalid parent");

        // This test should have no warnings since "invalid@uid" is actually valid
        assert!(
            parsed_entities.warns().is_empty(),
            "Should have no warnings for valid UID"
        );
    }

    #[test]
    fn test_warning_enum_non_object_parent_entry() {
        // Test that non-object parent entries generate proper warnings
        let entity_with_invalid_parents = json!({
            "uid": {
                "type": "Test::Type",
                "id": "test_entity"
            },
            "attrs": {},
            "parents": [
                "not_an_object",  // Invalid parent format
                {
                    "type": "ValidParent",
                    "id": "valid"
                }
            ]
        });

        let default_entities_data = json!({
            "test_entity".to_string(): entity_with_invalid_parents
        });

        let raw_data: HashMap<String, Value> =
            serde_json::from_value(default_entities_data).unwrap();
        let parsed_entities = parse_default_entities_with_warns(Some(raw_data))
            .expect("Should parse entity with invalid parents");

        // Should have warnings for non-object parent entries
        assert!(!parsed_entities.warns().is_empty(), "Should have warnings");

        let warnings = parsed_entities.warns();
        assert_eq!(warnings.len(), 1, "Should have exactly 1 warning");

        // Verify the warning type and content
        match &warnings[0] {
            DefaultEntityWarning::NonObjectParentEntry { entry_id, value } => {
                assert_eq!(entry_id, "test_entity");
                assert!(value.contains("not_an_object"));
            },
            DefaultEntityWarning::InvalidParentUid { .. } => panic!(
                "Expected NonObjectParentEntry warning, got {:?}",
                warnings[0]
            ),
        }
    }

    #[test]
    fn test_warning_enum_non_object_parent() {
        // Test that non-object parent entries generate proper warnings
        let entity_with_invalid_parents = json!({
            "uid": {
                "type": "Test::Type",
                "id": "test_entity"
            },
            "attrs": {},
            "parents": [
                "not_an_object",  // Invalid parent format
                {
                    "missing_type": "parent",  // Missing type field
                    "id": "parent3"
                }
            ]
        });

        let default_entities_data = json!({
            "test_entity".to_string(): entity_with_invalid_parents
        });

        let raw_data: HashMap<String, Value> =
            serde_json::from_value(default_entities_data).unwrap();
        let parsed_entities = parse_default_entities_with_warns(Some(raw_data))
            .expect("Should parse entity with invalid parents");

        // Should have warnings for non-object parent entries
        assert!(!parsed_entities.warns().is_empty(), "Should have warnings");

        let warnings = parsed_entities.warns();
        assert_eq!(warnings.len(), 2, "Should have exactly 2 warnings");

        // Both should be NonObjectParentEntry warnings
        for warning in warnings {
            match warning {
                DefaultEntityWarning::NonObjectParentEntry { entry_id, value } => {
                    assert_eq!(entry_id, "test_entity");
                    assert!(!value.is_empty());
                },
                DefaultEntityWarning::InvalidParentUid { .. } => {
                    panic!("Expected NonObjectParentEntry warning, got {warning:?}")
                },
            }
        }
    }

    #[test]
    fn test_warning_enum_multiple_warnings() {
        // Test that multiple different warnings are properly captured
        let entity_with_multiple_issues = json!({
            "uid": {
                "type": "Test::Type",
                "id": "test_entity"
            },
            "attrs": {},
            "parents": [
                "not_an_object",  // Invalid parent format
                {
                    "missing_type": "parent",  // Missing type field
                    "id": "parent3"
                }
            ]
        });

        let default_entities_data = json!({
            "test_entity".to_string(): entity_with_multiple_issues
        });

        let raw_data: HashMap<String, Value> =
            serde_json::from_value(default_entities_data).unwrap();
        let parsed_entities = parse_default_entities_with_warns(Some(raw_data))
            .expect("Should parse entity with multiple issues");

        // Should have multiple warnings
        let warnings = parsed_entities.warns();
        assert_eq!(warnings.len(), 2, "Should have exactly 2 warnings");

        // Both should be NonObjectParentEntry warnings
        for warning in warnings {
            match warning {
                DefaultEntityWarning::NonObjectParentEntry { entry_id, value } => {
                    assert_eq!(entry_id, "test_entity");
                    assert!(!value.is_empty());
                },
                DefaultEntityWarning::InvalidParentUid { .. } => {
                    panic!("Expected NonObjectParentEntry warning, got {warning:?}")
                },
            }
        }
    }

    #[test]
    fn test_warning_enum_display_format() {
        // Test that warnings have proper display formatting
        let warning = DefaultEntityWarning::InvalidParentUid {
            entry_id: "test_entity".to_string(),
            parent_uid_str: "Test::Parent::\"invalid@uid\"".to_string(),
            error: "invalid character".to_string(),
        };

        let display_string = warning.to_string();
        assert!(display_string.contains("test_entity"));
        assert!(display_string.contains("Test::Parent"));
        assert!(display_string.contains("invalid character"));

        let warning2 = DefaultEntityWarning::NonObjectParentEntry {
            entry_id: "test_entity".to_string(),
            value: "\"not_an_object\"".to_string(),
        };

        let display_string2 = warning2.to_string();
        assert!(display_string2.contains("test_entity"));
        assert!(display_string2.contains("not_an_object"));
    }
}