cedar-policy 4.10.0

Cedar is a language for defining permissions as policies, which describe who should have access to what.
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
/*
 * Copyright Cedar Contributors
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

//! JSON FFI entry points for converting between JSON and Cedar formats. The
//! Cedar Wasm conversion functions are generated from the functions in this
//! file.

use super::utils::JsonValueWithNoDuplicateKeys;
use super::{DetailedError, Policy, Schema, Template};
use crate::api::{PolicySet, StringifiedPolicySet};
use serde::{Deserialize, Serialize};
use std::str::FromStr;
#[cfg(feature = "wasm")]
use wasm_bindgen::prelude::wasm_bindgen;

#[cfg(feature = "wasm")]
extern crate tsify;

/// Takes a `PolicySet` represented as string and return the policies
/// and templates split into vecs and sorted by id.
#[cfg_attr(feature = "wasm", wasm_bindgen(js_name = "policySetTextToParts"))]
pub fn policy_set_text_to_parts(policyset_str: &str) -> PolicySetTextToPartsAnswer {
    let parsed_ps: Result<PolicySet, _> = PolicySet::from_str(policyset_str);
    match parsed_ps {
        Ok(policy_set) => {
            if let Some(StringifiedPolicySet {
                policies,
                policy_templates,
            }) = policy_set.stringify()
            {
                PolicySetTextToPartsAnswer::Success {
                    policies,
                    policy_templates,
                }
            } else {
                // This should never happen due to the nature of the input but we cover it
                // just in case, to future-proof the interface
                PolicySetTextToPartsAnswer::Failure {
                    errors: vec![DetailedError::from_str(
                        "Policy set input contained template linked policies",
                    )
                    .unwrap_or_default()],
                }
            }
        }
        Err(e) => PolicySetTextToPartsAnswer::Failure {
            errors: vec![(&e).into()],
        },
    }
}

/// Return the Cedar (textual) representation of a policy.
#[cfg_attr(feature = "wasm", wasm_bindgen(js_name = "policyToText"))]
pub fn policy_to_text(policy: Policy) -> PolicyToTextAnswer {
    match policy.parse(None) {
        Ok(policy) => PolicyToTextAnswer::Success {
            text: policy.to_string(),
        },
        Err(e) => PolicyToTextAnswer::Failure {
            errors: vec![e.into()],
        },
    }
}

/// Return the Cedar (textual) representation of a template.
#[cfg_attr(feature = "wasm", wasm_bindgen(js_name = "templateToText"))]
pub fn template_to_text(template: Template) -> PolicyToTextAnswer {
    match template.parse(None) {
        Ok(template) => PolicyToTextAnswer::Success {
            text: template.to_string(),
        },
        Err(e) => PolicyToTextAnswer::Failure {
            errors: vec![e.into()],
        },
    }
}

/// Return the JSON representation of a policy.
#[cfg_attr(feature = "wasm", wasm_bindgen(js_name = "policyToJson"))]
pub fn policy_to_json(policy: Policy) -> PolicyToJsonAnswer {
    match policy.parse(None) {
        Ok(policy) => match policy.to_json() {
            Ok(json) => PolicyToJsonAnswer::Success { json: json.into() },
            Err(e) => PolicyToJsonAnswer::Failure {
                errors: vec![miette::Report::new(e).into()],
            },
        },
        Err(e) => PolicyToJsonAnswer::Failure {
            errors: vec![e.into()],
        },
    }
}

/// Return the JSON representation of a template.
#[cfg_attr(feature = "wasm", wasm_bindgen(js_name = "templateToJson"))]
pub fn template_to_json(template: Template) -> PolicyToJsonAnswer {
    match template.parse(None) {
        Ok(template) => match template.to_json() {
            Ok(json) => PolicyToJsonAnswer::Success { json: json.into() },
            Err(e) => PolicyToJsonAnswer::Failure {
                errors: vec![miette::Report::new(e).into()],
            },
        },
        Err(e) => PolicyToJsonAnswer::Failure {
            errors: vec![e.into()],
        },
    }
}

/// Return the Cedar (textual) representation of a schema.
#[cfg_attr(feature = "wasm", wasm_bindgen(js_name = "schemaToText"))]
pub fn schema_to_text(schema: Schema) -> SchemaToTextAnswer {
    match schema.parse_schema_fragment() {
        Ok((schema_frag, warnings)) => {
            match schema_frag.to_cedarschema() {
                Ok(text) => {
                    // Before returning, check that the schema fragment corresponds to a valid schema
                    if let Err(e) = TryInto::<crate::Schema>::try_into(schema_frag) {
                        SchemaToTextAnswer::Failure {
                            errors: vec![miette::Report::new(e).into()],
                        }
                    } else {
                        SchemaToTextAnswer::Success {
                            text,
                            warnings: warnings.map(|e| miette::Report::new(e).into()).collect(),
                        }
                    }
                }
                Err(e) => SchemaToTextAnswer::Failure {
                    errors: vec![miette::Report::new(e).into()],
                },
            }
        }
        Err(e) => SchemaToTextAnswer::Failure {
            errors: vec![e.into()],
        },
    }
}

/// Return the JSON representation of a schema.
#[cfg_attr(feature = "wasm", wasm_bindgen(js_name = "schemaToJson"))]
pub fn schema_to_json(schema: Schema) -> SchemaToJsonAnswer {
    match schema.parse_schema_fragment() {
        Ok((schema_frag, warnings)) => match schema_frag.to_json_value() {
            Ok(json) => {
                // Before returning, check that the schema fragment corresponds to a valid schema
                if let Err(e) = crate::Schema::from_json_value(json.clone()) {
                    SchemaToJsonAnswer::Failure {
                        errors: vec![miette::Report::new(e).into()],
                    }
                } else {
                    SchemaToJsonAnswer::Success {
                        json: json.into(),
                        warnings: warnings.map(|e| miette::Report::new(e).into()).collect(),
                    }
                }
            }
            Err(e) => SchemaToJsonAnswer::Failure {
                errors: vec![miette::Report::new(e).into()],
            },
        },
        Err(e) => SchemaToJsonAnswer::Failure {
            errors: vec![e.into()],
        },
    }
}

/// Convert a Cedar schema string to JSON format with resolved types.
///
/// This function resolves ambiguous "`EntityOrCommon`" types to their specific
/// Entity or `CommonType` classifications using the schema's type definitions.
/// This is primarily meant to be used when working with schemas programmatically,
/// for example when creating a schema building UI.
#[cfg_attr(
    feature = "wasm",
    wasm_bindgen(js_name = "schemaToJsonWithResolvedTypes")
)]
pub fn schema_to_json_with_resolved_types(schema_str: &str) -> SchemaToJsonWithResolvedTypesAnswer {
    match crate::api::schema_str_to_json_with_resolved_types(schema_str) {
        Ok((json_value, warnings)) => SchemaToJsonWithResolvedTypesAnswer::Success {
            json: json_value.into(),
            warnings: warnings.iter().map(std::convert::Into::into).collect(),
        },
        Err(error) => {
            // Convert CedarSchemaError to DetailedError
            SchemaToJsonWithResolvedTypesAnswer::Failure {
                errors: vec![(&error).into()],
            }
        }
    }
}

/// Result of converting a policy or template to the Cedar format
#[derive(Debug, Serialize, Deserialize)]
#[serde(tag = "type")]
#[serde(rename_all = "camelCase")]
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
#[cfg_attr(feature = "wasm", tsify(into_wasm_abi, from_wasm_abi))]
pub enum PolicyToTextAnswer {
    /// Represents a successful call
    Success {
        /// Cedar format policy
        text: String,
    },
    /// Represents a failed call (e.g., because the input is ill-formed)
    Failure {
        /// Errors
        errors: Vec<DetailedError>,
    },
}

/// Result of converting a policyset as a string into its Cedar
/// format components
#[derive(Debug, Serialize, Deserialize)]
#[serde(tag = "type")]
#[serde(rename_all = "camelCase")]
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
#[cfg_attr(feature = "wasm", tsify(into_wasm_abi, from_wasm_abi))]
pub enum PolicySetTextToPartsAnswer {
    /// Represents a successful call
    Success {
        /// Cedar format policies
        policies: Vec<String>,
        /// Cedar format policy templates
        policy_templates: Vec<String>,
    },
    /// Represents a failed call (e.g., because the input is ill-formed)
    Failure {
        /// Errors
        errors: Vec<DetailedError>,
    },
}

/// Result of converting a policy or template to JSON
#[derive(Debug, Serialize, Deserialize)]
#[serde(tag = "type")]
#[serde(rename_all = "camelCase")]
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
#[cfg_attr(feature = "wasm", tsify(into_wasm_abi, from_wasm_abi))]
pub enum PolicyToJsonAnswer {
    /// Represents a successful call
    Success {
        /// JSON format policy
        #[cfg_attr(feature = "wasm", tsify(type = "PolicyJson"))]
        json: JsonValueWithNoDuplicateKeys,
    },
    /// Represents a failed call (e.g., because the input is ill-formed)
    Failure {
        /// Errors
        errors: Vec<DetailedError>,
    },
}

/// Result of converting a schema to the Cedar format
#[derive(Debug, Serialize, Deserialize)]
#[serde(tag = "type")]
#[serde(rename_all = "camelCase")]
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
#[cfg_attr(feature = "wasm", tsify(into_wasm_abi, from_wasm_abi))]
pub enum SchemaToTextAnswer {
    /// Represents a successful call
    Success {
        /// Cedar format schema
        text: String,
        /// Warnings
        warnings: Vec<DetailedError>,
    },
    /// Represents a failed call (e.g., because the input is ill-formed)
    Failure {
        /// Errors
        errors: Vec<DetailedError>,
    },
}

/// Result of converting a schema to JSON
#[derive(Debug, Serialize, Deserialize)]
#[serde(tag = "type")]
#[serde(rename_all = "camelCase")]
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
#[cfg_attr(feature = "wasm", tsify(into_wasm_abi, from_wasm_abi))]
pub enum SchemaToJsonAnswer {
    /// Represents a successful call
    Success {
        /// JSON format schema
        #[cfg_attr(feature = "wasm", tsify(type = "SchemaJson<string>"))]
        json: JsonValueWithNoDuplicateKeys,
        /// Warnings
        warnings: Vec<DetailedError>,
    },
    /// Represents a failed call (e.g., because the input is ill-formed)
    Failure {
        /// Errors
        errors: Vec<DetailedError>,
    },
}

/// Result of converting a schema to JSON with resolved types
#[derive(Debug, Serialize, Deserialize)]
#[serde(tag = "type")]
#[serde(rename_all = "camelCase")]
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
#[cfg_attr(feature = "wasm", tsify(into_wasm_abi, from_wasm_abi))]
pub enum SchemaToJsonWithResolvedTypesAnswer {
    /// Represents a successful call
    Success {
        /// JSON format schema with resolved types
        #[cfg_attr(feature = "wasm", tsify(type = "SchemaJson<string>"))]
        json: JsonValueWithNoDuplicateKeys,
        /// Warnings
        warnings: Vec<DetailedError>,
    },
    /// Represents a failed call (e.g., because the input is ill-formed)
    Failure {
        /// Errors
        errors: Vec<DetailedError>,
    },
}

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

    use crate::ffi::test_utils::*;
    use assert_json_diff::assert_json_eq;
    use cool_asserts::assert_matches;
    use serde_json::json;

    #[test]
    fn test_policy_to_json() {
        let text = r#"
            permit(principal, action, resource)
            when { principal has "Email" && principal.Email == "a@a.com" };
        "#;
        let result = policy_to_json(Policy::Cedar(text.into()));
        let expected = json!({
            "effect": "permit",
            "principal": {
                "op": "All"
            },
            "action": {
                "op": "All"
            },
            "resource": {
                "op": "All"
            },
            "conditions": [
                {
                    "kind": "when",
                    "body": {
                        "&&": {
                            "left": {
                                "has": {
                                    "left": {
                                        "Var": "principal"
                                    },
                                    "attr": "Email"
                                }
                            },
                            "right": {
                                "==": {
                                    "left": {
                                        ".": {
                                            "left": {
                                                "Var": "principal"
                                            },
                                            "attr": "Email"
                                        }
                                    },
                                    "right": {
                                        "Value": "a@a.com"
                                    }
                                }
                            }
                        }
                    }
                }
            ]
        });
        assert_matches!(result, PolicyToJsonAnswer::Success { json } =>
          assert_eq!(json, expected.into())
        );
    }

    #[test]
    fn test_policy_to_json_error() {
        let text = r#"
            permit(principal, action, resource)
            when { principal has "Email" && principal.Email == };
        "#;
        let result = policy_to_json(Policy::Cedar(text.into()));
        assert_matches!(result, PolicyToJsonAnswer::Failure { errors } => {
            assert_exactly_one_error(
                &errors,
                "failed to parse policy from string: unexpected token `}`",
                None,
            );
        });
    }

    #[test]
    fn test_policy_to_text() {
        let json = json!({
            "effect": "permit",
            "action": {
                "entity": {
                    "id": "pop",
                    "type": "Action"
                },
                "op": "=="
            },
            "principal": {
                "entity": {
                    "id": "DeathRowRecords",
                    "type": "UserGroup"
                },
                "op": "in"
            },
            "resource": {
                "op": "All"
            },
            "conditions": []
        });
        let result = policy_to_text(Policy::Json(json.into()));
        assert_matches!(result, PolicyToTextAnswer::Success { text } => {
            assert_eq!(
                &text,
                "permit(principal in UserGroup::\"DeathRowRecords\", action == Action::\"pop\", resource);"
            );
        });
    }

    #[test]
    fn test_template_to_json() {
        let text = r"
            permit(principal in ?principal, action, resource);
        ";
        let result = template_to_json(Template::Cedar(text.into()));
        let expected = json!({
            "effect": "permit",
            "principal": {
                "op": "in",
                "slot": "?principal"
            },
            "action": {
                "op": "All"
            },
            "resource": {
                "op": "All"
            },
            "conditions": []
        });
        assert_matches!(result, PolicyToJsonAnswer::Success { json } =>
          assert_eq!(json, expected.into())
        );
    }

    #[test]
    fn test_template_to_text() {
        let json = json!({
            "effect": "permit",
            "principal": {
                "op": "All"
            },
            "action": {
                "op": "All"
            },
            "resource": {
                "op": "in",
                "slot": "?resource"
            },
            "conditions": []
        });
        let result = template_to_text(Template::Json(json.into()));
        assert_matches!(result, PolicyToTextAnswer::Success { text } => {
            assert_eq!(
                &text,
                "permit(principal, action, resource in ?resource);"
            );
        });
    }

    #[test]
    fn test_template_to_text_error() {
        let json = json!({
            "effect": "permit",
            "action": {
                "entity": {
                    "id": "pop",
                    "type": "Action"
                },
                "op": "=="
            },
            "principal": {
                "entity": {
                    "id": "DeathRowRecords",
                    "type": "UserGroup"
                },
                "op": "in"
            },
            "resource": {
                "op": "All"
            },
            "conditions": []
        });
        let result = template_to_text(Template::Json(json.into()));
        assert_matches!(result, PolicyToTextAnswer::Failure { errors } => {
            assert_exactly_one_error(
                &errors,
                "failed to parse template from JSON: error deserializing a policy/template from JSON: expected a template, got a static policy",
                Some("a template should include slot(s) `?principal` or `?resource`"),
            );
        });
    }

    #[test]
    fn test_schema_to_json() {
        let text = r#"
            entity User = { "name": String };
            action sendMessage appliesTo {principal: User, resource: User};
        "#;
        let result = schema_to_json(Schema::Cedar(text.into()));
        let expected = json!({
        "": {
            "entityTypes": {
                "User": {
                    "shape": {
                        "type": "Record",
                        "attributes": {
                            "name": {"type": "EntityOrCommon", "name": "String"} // this will resolve to the builtin type `String` unless the user defines their own common or entity type `String` in the empty namespace, in another fragment
                        }
                    }
                }
            },
            "actions": {
                "sendMessage": {
                    "appliesTo": {
                        "resourceTypes": ["User"],
                        "principalTypes": ["User"]
                    }
                }}
            }
        });
        assert_matches!(result, SchemaToJsonAnswer::Success { json, warnings:_ } =>
          assert_eq!(json, expected.into())
        );
    }

    #[test]
    fn test_schema_to_json_error() {
        let text = r"
            action sendMessage appliesTo {principal: User, resource: User};
        ";
        let result = schema_to_json(Schema::Cedar(text.into()));
        assert_matches!(result, SchemaToJsonAnswer::Failure { errors } => {
            assert_exactly_one_error(
                &errors,
                "failed to resolve types: User, User",
                Some("`User` has not been declared as an entity type"),
            );
        });
    }

    #[test]
    fn test_schema_to_text() {
        let json = json!({
        "": {
            "entityTypes": {
                "User": {
                    "shape": {
                        "type": "Record",
                        "attributes": {
                            "name": {"type": "String"}
                        }
                    }
                }
            },
            "actions": {
                "sendMessage": {
                    "appliesTo": {
                        "resourceTypes": ["User"],
                        "principalTypes": ["User"]
                    }
                }}
            }
        });
        let result = schema_to_text(Schema::Json(json.into()));
        assert_matches!(result, SchemaToTextAnswer::Success { text, warnings:_ } => {
            assert_eq!(
                &text,
                r#"entity User = {
  name: __cedar::String
};

action "sendMessage" appliesTo {
  principal: [User],
  resource: [User],
  context: {}
};
"#
            );
        });
    }

    #[test]
    fn policy_set_to_text_to_parts() {
        let policy_set_str = r#"
            permit(principal, action, resource)
            when { principal has "Email" && principal.Email == "a@a.com" };
            
            permit(principal in UserGroup::"DeathRowRecords", action == Action::"pop", resource);

            permit(principal in ?principal, action, resource);
        "#;

        let result = policy_set_text_to_parts(policy_set_str);
        assert_matches!(result, PolicySetTextToPartsAnswer::Success { policies, policy_templates } => {
            assert_eq!(policies.len(), 2);
            assert_eq!(policy_templates.len(), 1);
        });
    }

    #[test]
    fn test_policy_set_text_to_parts_parse_failure() {
        let invalid_input = "This is not a valid PolicySet string";

        let result = policy_set_text_to_parts(invalid_input);

        assert_matches!(result, PolicySetTextToPartsAnswer::Failure { errors } => {
            assert_exactly_one_error(
                &errors,
                "unexpected token `is`",
                None,
            );
        });
    }

    #[test]
    fn test_schema_to_json_with_resolved_types() {
        let schema_str = r#"
            entity User = { "name": String };
            action sendMessage appliesTo {principal: User, resource: User};
            namespace MyApp {
                entity AppUser = {
                    "name": __cedar::String
                };

                action view appliesTo {
                    principal: [AppUser],
                    resource: [AppUser],
                    context: {
                        prop1: Long
                    }
                };
            }
            namespace MyApp2 {
                entity AppUser = {
                    "name": __cedar::String
                };

                action view appliesTo {
                    principal: [AppUser],
                    resource: [AppUser],
                    context: {}
                };
            }
        "#;

        let result = schema_to_json_with_resolved_types(schema_str);
        match result {
            SchemaToJsonWithResolvedTypesAnswer::Success { json, warnings } => {
                let json_value: serde_json::Value = json.into();
                let json_str = serde_json::to_string(&json_value).unwrap();
                assert!(!json_str.contains("EntityOrCommon"));
                assert!(warnings.len() == 0);

                // Construct expected JSON structure
                let expected = json!({
                    "": {
                        "entityTypes": {
                            "User": {
                                "shape": {
                                    "type": "Record",
                                    "attributes": {
                                        "name": {"type": "String"}
                                    }
                                }
                            }
                        },
                        "actions": {
                            "sendMessage": {
                                "appliesTo": {
                                    "principalTypes": ["User"],
                                    "resourceTypes": ["User"]
                                }
                            }
                        }
                    },
                    "MyApp": {
                        "entityTypes": {
                            "AppUser": {
                                "shape": {
                                    "type": "Record",
                                    "attributes": {
                                        "name": {"type": "__cedar::String"}
                                    }
                                }
                            }
                        },
                        "actions": {
                            "view": {
                                "appliesTo": {
                                    "principalTypes": ["MyApp::AppUser"],
                                    "resourceTypes": ["MyApp::AppUser"],
                                    "context": {
                                        "type": "Record",
                                        "attributes": {
                                            "prop1": {"type": "Long"}
                                        }
                                    }
                                }
                            }
                        }
                    },
                    "MyApp2": {
                        "entityTypes": {
                            "AppUser": {
                                "shape": {
                                    "type": "Record",
                                    "attributes": {
                                        "name": {"type": "__cedar::String"}
                                    }
                                }
                            }
                        },
                        "actions": {
                            "view": {
                                "appliesTo": {
                                    "principalTypes": ["MyApp2::AppUser"],
                                    "resourceTypes": ["MyApp2::AppUser"]
                                }
                            }
                        }
                    }
                });

                assert_json_eq!(json_value, expected);
            }
            SchemaToJsonWithResolvedTypesAnswer::Failure { errors } => {
                panic!("Expected success but got errors: {:?}", errors);
            }
        }
    }

    #[test]
    fn test_schema_to_json_with_resolved_types_simple() {
        let schema_str = r#"
            entity User;
            entity Document;
            action view appliesTo {principal: User, resource: Document};
        "#;

        let result = schema_to_json_with_resolved_types(schema_str);
        match result {
            SchemaToJsonWithResolvedTypesAnswer::Success { json, warnings } => {
                let json_value: serde_json::Value = json.into();
                let json_str = serde_json::to_string(&json_value).unwrap();
                assert!(!json_str.contains("EntityOrCommon"));
                assert!(warnings.len() == 0);

                // Construct expected JSON structure
                let expected = json!({
                    "": {
                        "entityTypes": {
                            "User": {},
                            "Document": {}
                        },
                        "actions": {
                            "view": {
                                "appliesTo": {
                                    "principalTypes": ["User"],
                                    "resourceTypes": ["Document"]
                                }
                            }
                        }
                    }
                });

                assert_json_eq!(json_value, expected);
            }
            SchemaToJsonWithResolvedTypesAnswer::Failure { errors } => {
                panic!("Expected success but got errors: {:?}", errors);
            }
        }
    }

    #[test]
    fn test_schema_to_json_with_resolved_types_common_type() {
        let schema_str = r#"
            type MyString = String;
            entity User = { "name": MyString };
            action sendMessage appliesTo {principal: User, resource: User};
        "#;

        let result = schema_to_json_with_resolved_types(schema_str);
        match result {
            SchemaToJsonWithResolvedTypesAnswer::Success { json, warnings } => {
                let json_value: serde_json::Value = json.into();
                let json_str = serde_json::to_string(&json_value).unwrap();
                assert!(!json_str.contains("EntityOrCommon"));
                assert!(warnings.len() == 0);

                // Construct expected JSON structure
                let expected = json!({
                    "": {
                        "commonTypes": {
                            "MyString": {"type": "String"}
                        },
                        "entityTypes": {
                            "User": {
                                "shape": {
                                    "type": "Record",
                                    "attributes": {
                                        "name": {"type": "MyString"}
                                    }
                                }
                            }
                        },
                        "actions": {
                            "sendMessage": {
                                "appliesTo": {
                                    "principalTypes": ["User"],
                                    "resourceTypes": ["User"]
                                }
                            }
                        }
                    }
                });

                assert_json_eq!(json_value, expected);
            }
            SchemaToJsonWithResolvedTypesAnswer::Failure { errors } => {
                panic!("Expected success but got errors: {:?}", errors);
            }
        }
    }

    #[test]
    fn test_shadowing_types() {
        insta::glob!("test_schemas/shadowed_*.cedarschema", |path| {
            let schema_str = std::fs::read_to_string(path).unwrap();
            let result = schema_to_json_with_resolved_types(&schema_str);
            match result {
                SchemaToJsonWithResolvedTypesAnswer::Success { json, warnings } => {
                    let json_value: serde_json::Value = json.into();

                    let json_str = serde_json::to_string(&json_value).unwrap();

                    assert!(!json_str.contains("EntityOrCommon"));
                    assert!(warnings.len() > 0);
                }
                SchemaToJsonWithResolvedTypesAnswer::Failure { errors } => {
                    panic!("Expected success but got errors: {:?}", errors);
                }
            }
        });
    }

    #[test]
    fn test_schema_resolution_round_trip() {
        insta::glob!("test_schemas/*.cedarschema", |path| {
            let mut insta_settings = insta::Settings::clone_current();
            insta_settings.set_sort_maps(true);

            // Set snapshot suffix to include the file name
            let file_name = path.file_stem().unwrap().to_str().unwrap();
            insta_settings.set_snapshot_suffix(file_name);

            let schema_str = std::fs::read_to_string(path).unwrap();

            // Parse original schema to ValidatorSchema
            let validator_schema_direct_parse = match crate::Schema::from_str(&schema_str) {
                Ok(schema) => schema,
                Err(e) => panic!("Failed to parse original schema from {:?}: {:?}", path, e),
            };

            // Convert to JSON with resolved types
            let result = schema_to_json_with_resolved_types(&schema_str);
            let resolved_json = match result {
                SchemaToJsonWithResolvedTypesAnswer::Success { json, .. } => json,
                SchemaToJsonWithResolvedTypesAnswer::Failure { errors } => {
                    panic!(
                        "Failed to convert schema to JSON with resolved types for {:?}: {:?}",
                        path, errors
                    );
                }
            };
            let resolved_json_stringified = serde_json::to_string_pretty(&resolved_json)
                .expect("Serialization of json failed!");

            insta_settings.bind(|| {
                insta::assert_json_snapshot!(resolved_json);
            });

            // Parse resolved JSON back to ValidatorSchema
            let validator_schema_round_tripped =
                match crate::Schema::from_json_str(&resolved_json_stringified) {
                    Ok(schema) => schema,
                    Err(e) => panic!(
                        "Failed to parse resolved JSON back to schema for {:?}: {:?}",
                        path, e
                    ),
                };

            // Compare entity types and action definitions for semantic equivalence
            let entity_types_v1: std::collections::HashSet<_> =
                validator_schema_direct_parse.entity_types().collect();
            let entity_types_v2: std::collections::HashSet<_> =
                validator_schema_round_tripped.entity_types().collect();
            assert_eq!(
                entity_types_v1, entity_types_v2,
                "Entity types should be identical for {:?}",
                path
            );

            let action_ids_v1: std::collections::HashSet<_> =
                validator_schema_direct_parse.actions().collect();
            let action_ids_v2: std::collections::HashSet<_> =
                validator_schema_round_tripped.actions().collect();
            assert_eq!(
                action_ids_v1, action_ids_v2,
                "Action definitions should be identical for {:?}",
                path
            );
        });
    }
}