cedarling 0.0.64

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
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
// 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.

//! Integration tests for the new policy store loader.
//!
//! These tests verify that:
//! - Directory-based policy stores load correctly and can be used for authorization
//! - Cedar Archive (.cjar) files load correctly and can be used for authorization
//! - Manifest validation works as expected (checksums, policy store ID matching)
//! - Error cases are handled properly at the API level
//!
//! The tests use the same `Cedarling` API and patterns as other integration tests,
//! ensuring the new loader paths work end-to-end.
//!
//! ## Platform Support
//!
//! - **Native platforms**: All tests run, including directory/file-based loading
//! - **WASM**: Tests using `CjarUrl` and `load_policy_store_archive_bytes` work,
//!   as they don't require filesystem access. Directory and file-based tests are
//!   skipped with `#[cfg(not(target_arch = "wasm32"))]`.

#[cfg(not(target_arch = "wasm32"))]
use std::fs;
#[cfg(not(target_arch = "wasm32"))]
use std::io::Read;
use std::io::Write;

use serde_json::json;
#[cfg(not(target_arch = "wasm32"))]
use tempfile::TempDir;
use tokio::test;
#[cfg(not(target_arch = "wasm32"))]
use zip::read::ZipArchive;

use crate::common::policy_store::test_utils::PolicyStoreTestBuilder;

use crate::tests::utils::cedarling_util::{get_cedarling_with_callback, get_config};
use crate::tests::utils::test_helpers::{create_test_principal, create_test_unsigned_request};
use crate::{
    BootstrapConfig, Cedarling, DataStoreConfig, EntityData, PolicyStoreConfig, PolicyStoreSource,
    TrustedIssuerLoadingInfo,
};

// ============================================================================
// Helper Functions
// ============================================================================

/// Creates a policy store builder configured for authorization testing.
///
/// This builder includes:
/// - A schema with User, Resource, and Action types
/// - A simple "allow-read" policy
/// - A "deny-write-guest" policy based on `user_type` attribute
fn create_authz_policy_store_builder() -> PolicyStoreTestBuilder {
    PolicyStoreTestBuilder::new("a1b2c3d4e5f6a7b8")
        .with_name("Integration Test Policy Store")
        .with_schema(
            r#"namespace TestApp {
    entity User {
        name: String,
        user_type: String,
    };
    entity Resource {
        name: String,
    };
    
    action "read" appliesTo {
        principal: [User],
        resource: [Resource]
    };
    
    action "write" appliesTo {
        principal: [User],
        resource: [Resource]
    };
}
"#,
        )
        .with_policy(
            "allow-read",
            r#"@id("allow-read")
permit(
    principal,
    action == TestApp::Action::"read",
    resource
);"#,
        )
        .with_policy(
            "deny-write-guest",
            r#"@id("deny-write-guest")
forbid(
    principal,
    action == TestApp::Action::"write",
    resource
) when { principal.user_type == "guest" };"#,
        )
}

/// Extracts a zip archive to a temporary directory.
#[cfg(not(target_arch = "wasm32"))]
fn extract_archive_to_temp_dir(archive_bytes: &[u8]) -> TempDir {
    let temp_dir = TempDir::new().expect("Failed to create temp directory");
    let mut zip_archive =
        ZipArchive::new(std::io::Cursor::new(archive_bytes)).expect("Failed to read zip archive");

    for i in 0..zip_archive.len() {
        let mut file = zip_archive.by_index(i).expect("Failed to get zip entry");
        let file_path = temp_dir.path().join(file.name());

        if file.is_dir() {
            fs::create_dir_all(&file_path).expect("Failed to create directory");
        } else {
            if let Some(parent) = file_path.parent() {
                fs::create_dir_all(parent).expect("Failed to create parent directory");
            }
            let mut contents = Vec::new();
            file.read_to_end(&mut contents)
                .expect("Failed to read file contents");
            fs::write(&file_path, contents).expect("Failed to write file");
        }
    }

    temp_dir
}

/// Creates a Cedarling instance from a directory path.
async fn get_cedarling_from_directory(path: std::path::PathBuf) -> Cedarling {
    get_cedarling_with_callback(PolicyStoreSource::Directory(path), |_| {}).await
}

/// Creates a Cedarling instance from an archive file path.
async fn get_cedarling_from_cjar_file(path: std::path::PathBuf) -> Cedarling {
    get_cedarling_with_callback(PolicyStoreSource::CjarFile(path), |_| {}).await
}

/// Cedar schema for [`test_load_from_cjar_with_multi_policy_file`] (`TestApp` read/write).
#[cfg(not(target_arch = "wasm32"))]
const MULTI_POLICY_CJAR_TEST_SCHEMA: &str = r#"namespace TestApp {
    entity User {
        name: String,
        user_type: String,
    };
    entity Resource {
        name: String,
    };
    action "read" appliesTo {
        principal: [User],
        resource: [Resource]
    };
    action "write" appliesTo {
        principal: [User],
        resource: [Resource]
    };
}
"#;

/// Combined policies: read permit, general write permit, guest-only write forbid.
#[cfg(not(target_arch = "wasm32"))]
const MULTI_POLICY_COMBINED_CEDAR: &str = r#"@id("allow-read")
permit(
    principal,
    action == TestApp::Action::"read",
    resource
);

@id("allow-write-all")
permit(
    principal,
    action == TestApp::Action::"write",
    resource
);

@id("deny-write-guest")
forbid(
    principal,
    action == TestApp::Action::"write",
    resource
) when { principal.user_type == "guest" };"#;

#[cfg(not(target_arch = "wasm32"))]
async fn multi_policy_cjar_unsigned_decision(
    cedarling: &Cedarling,
    action: &str,
    user: EntityData,
) -> bool {
    let resource = create_test_principal(
        "TestApp::Resource",
        "resource1",
        json!({"name": "Test Resource"}),
    )
    .expect("Failed to create resource");
    let request = create_test_unsigned_request(action, Some(user), resource);
    cedarling
        .authorize_unsigned(request)
        .await
        .expect("Authorization should succeed")
        .decision
}

fn create_jwt_cedarling_config(
    policy_store_source: PolicyStoreSource,
    jwt_sig_validation: bool,
) -> BootstrapConfig {
    create_jwt_cedarling_config_with_loader(policy_store_source, jwt_sig_validation, false)
}

fn create_jwt_cedarling_config_with_loader(
    policy_store_source: PolicyStoreSource,
    jwt_sig_validation: bool,
    async_loading: bool,
) -> BootstrapConfig {
    use crate::jwt_config::{JwtConfig, TrustedIssuerLoaderConfig, WorkersCount};
    use crate::{AuthorizationConfig, BootstrapConfig, LogConfig, LogTypeConfig};

    let trusted_issuer_loader = if async_loading {
        TrustedIssuerLoaderConfig::Async {
            workers: WorkersCount::MIN,
        }
    } else {
        TrustedIssuerLoaderConfig::Sync {
            workers: WorkersCount::MIN,
        }
    };

    BootstrapConfig {
        application_name: "test_app".to_string(),
        log_config: LogConfig {
            log_type: LogTypeConfig::Off,
            log_level: crate::LogLevel::DEBUG,
        },
        policy_store_config: PolicyStoreConfig {
            source: policy_store_source,
            ..Default::default()
        },
        jwt_config: JwtConfig {
            jwks: None,
            jwt_sig_validation,
            jwt_status_validation: false,
            trusted_issuer_loader,
            ..Default::default()
        }
        .allow_all_algorithms(),
        authorization_config: AuthorizationConfig {
            decision_log_default_jwt_id: "jti".to_string(),
            strict_schema_validation: true,
        },
        lock_config: None,
        max_default_entities: None,
        max_base64_size: None,
        data_store_config: DataStoreConfig::default(),
        http_client_config: crate::HttpClientConfig::default(),
    }
}

fn create_jwt_trusted_issuer_json(oidc_endpoint: &str) -> String {
    format!(
        r#"{{
        "id": "mock_issuer",
        "name": "Jans",
        "description": "Test issuer for JWT validation",
        "configuration_endpoint": "{oidc_endpoint}",
        "token_metadata": {{
            "access_token": {{
                "entity_type_name": "Jans::Access_token"
            }},
            "id_token": {{
                "entity_type_name": "Jans::Id_token"
            }},
            "userinfo_token": {{
                "entity_type_name": "Jans::Userinfo_token"
            }}
        }}
    }}"#
    )
}

/// Creates a trusted issuer JSON with a custom issuer ID.
fn create_jwt_trusted_issuer_json_with_id(issuer_id: &str, oidc_endpoint: &str) -> String {
    format!(
        r#"{{
        "id": "{issuer_id}",
        "name": "Jans",
        "description": "Test issuer for JWT validation",
        "configuration_endpoint": "{oidc_endpoint}",
        "token_metadata": {{
            "access_token": {{
                "entity_type_name": "Jans::Access_token"
            }},
            "id_token": {{
                "entity_type_name": "Jans::Id_token"
            }},
            "userinfo_token": {{
                "entity_type_name": "Jans::Userinfo_token"
            }}
        }}
    }}"#
    )
}

// Schema that works with JWT-based authorization
// Uses Jans namespace to match the default entity builder
const SCHEMA: &str = r#"namespace Jans {
    type Url = {"host": String, "path": String, "protocol": String};
    entity TrustedIssuer = {"issuer_entity_id": Url};
    entity Access_token = {
        aud: String,
        exp: Long,
        iat: Long,
        iss: TrustedIssuer,
        jti: String,
        client_id?: String,
        org_id?: String,
    };
    entity Id_token = {
        aud: Set<String>,
        exp: Long,
        iat: Long,
        iss: TrustedIssuer,
        jti: String,
        sub: String,
    };
    entity Userinfo_token = {
        country?: String,
        exp?: Long,
        iat?: Long,
        iss: TrustedIssuer,
        jti: String,
        sub: String,
        role?: Set<String>,
    };
    entity Workload {
        iss: TrustedIssuer,
        access_token: Access_token,
        client_id: String,
        org_id?: String,
    };
    entity User {
        userinfo_token: Userinfo_token,
        country?: String,
        role?: Set<String>,
        sub: String,
    };
    entity Role;
    entity Resource {
        org_id?: String,
        country?: String,
    };
    action "Read" appliesTo {
        principal: [Workload, User, Role],
        resource: [Resource],
        context: {}
    };
}
"#;

// ============================================================================
// Directory-Based Loading Tests
// ============================================================================

/// Test that a policy store loaded from a directory works for authorization.
#[test]
#[cfg(not(target_arch = "wasm32"))]
async fn test_load_from_directory_and_authorize_success() {
    // Build archive and extract to temp directory

    use crate::tests::utils::test_helpers::{create_test_principal, create_test_unsigned_request};
    let builder = create_authz_policy_store_builder();
    let archive = builder
        .build_archive()
        .expect("Failed to build test archive");
    let temp_dir = extract_archive_to_temp_dir(&archive);

    // Create Cedarling from directory
    let cedarling = get_cedarling_from_directory(temp_dir.path().to_path_buf()).await;

    // Create an authorization request
    let request = create_test_unsigned_request(
        "TestApp::Action::\"read\"",
        Some(
            create_test_principal(
                "TestApp::User",
                "user1",
                json!({"name": "Test User", "user_type": "admin"}),
            )
            .expect("Failed to create principal"),
        ),
        create_test_principal(
            "TestApp::Resource",
            "resource1",
            json!({"name": "Test Resource"}),
        )
        .expect("Failed to create resource"),
    );
    // Execute authorization
    let result = cedarling
        .authorize_unsigned(request)
        .await
        .expect("Authorization should succeed");

    // Verify the result - read action should be allowed
    assert!(
        result.decision,
        "Read action should be allowed by the allow-read policy"
    );
}

/// Test that the `TrustedIssuerLoadingInfo` trait works correctly on `Cedarling`.
#[test]
#[cfg(not(target_arch = "wasm32"))]
async fn test_trusted_issuer_loading_info_on_cedarling() {
    use crate::jwt::test_utils::MockServer;

    // Create mock server for OIDC/JWKS
    let mock_server = MockServer::new_with_defaults()
        .await
        .expect("Failed to create mock server");

    let issuer_url = mock_server.issuer();
    let oidc_endpoint = format!("{issuer_url}/.well-known/openid-configuration");

    // Create trusted issuer JSON that points to mock server
    let trusted_issuer_json = create_jwt_trusted_issuer_json(&oidc_endpoint);

    // Build the policy store with trusted issuer
    let builder = PolicyStoreTestBuilder::new("a1b2c3d4e5f6a7b8")
        .with_name("Loading Info Test Policy Store")
        .with_schema(SCHEMA)
        .with_policy(
            "allow-workload-read",
            r#"@id("allow-workload-read")
permit(
    principal is Jans::Workload,
    action == Jans::Action::"Read",
    resource is Jans::Resource
)when{
    principal.access_token.org_id == resource.org_id
};"#,
        )
        .with_trusted_issuer("mock_issuer", trusted_issuer_json);

    let archive = builder.build_archive().expect("Failed to build archive");
    let temp_dir = extract_archive_to_temp_dir(&archive);

    // Configure Cedarling with JWT validation enabled
    let config = create_jwt_cedarling_config(
        PolicyStoreSource::Directory(temp_dir.path().to_path_buf()),
        true,
    );

    let cedarling = crate::Cedarling::new(&config)
        .await
        .expect("Cedarling should initialize with JWT-enabled config");

    // Wait a bit for trusted issuer loading to complete
    tokio::time::sleep(tokio::time::Duration::from_millis(500)).await;

    // Test TrustedIssuerLoadingInfo trait methods
    // Should have 1 trusted issuer defined
    assert!(cedarling.is_trusted_issuer_loaded_by_name("mock_issuer"));
    assert!(!cedarling.is_trusted_issuer_loaded_by_name("NonExistent"));

    // Check by iss claim
    assert!(cedarling.is_trusted_issuer_loaded_by_iss(issuer_url.as_str()));
    assert!(!cedarling.is_trusted_issuer_loaded_by_iss("https://nonexistent.com"));

    // Count and percentage
    assert_eq!(cedarling.loaded_trusted_issuers_count(), 1);

    // Loaded and failed IDs
    let loaded_ids = cedarling.loaded_trusted_issuer_ids();
    assert_eq!(loaded_ids.len(), 1);
    assert!(loaded_ids.contains("mock_issuer"));

    let failed_ids = cedarling.failed_trusted_issuer_ids();
    assert!(failed_ids.is_empty());
}

/// Test that the `TrustedIssuerLoadingInfo` trait correctly tracks failed issuers on `Cedarling`.
#[test]
#[cfg(not(target_arch = "wasm32"))]
async fn test_trusted_issuer_loading_info_failed_issuer() {
    use crate::jwt::test_utils::MockServer;
    use std::time::{Duration, Instant};

    // Create a working mock server for successful issuer loading
    let working_mock_server = MockServer::new_with_defaults()
        .await
        .expect("Failed to create working mock server");
    let working_issuer_url = working_mock_server.issuer();
    let working_oidc_endpoint = format!("{working_issuer_url}/.well-known/openid-configuration");
    let working_issuer_json =
        create_jwt_trusted_issuer_json_with_id("working_issuer", &working_oidc_endpoint);

    // Create a failing mock server that returns 500 for OIDC config
    let failing_mock_server = MockServer::new_with_failing_oidc()
        .await
        .expect("Failed to create failing mock server");
    let failing_issuer_url = failing_mock_server.issuer();
    let failing_oidc_endpoint = format!("{failing_issuer_url}/.well-known/openid-configuration");
    let failing_issuer_json =
        create_jwt_trusted_issuer_json_with_id("failing_issuer", &failing_oidc_endpoint);

    // Build the policy store with both working and failing trusted issuers
    let builder = PolicyStoreTestBuilder::new("a1b2c3d4e5f6a7b8")
        .with_name("Mixed Loading Info Test Policy Store")
        .with_schema(SCHEMA)
        .with_policy(
            "allow-workload-read",
            r#"@id("allow-workload-read")
permit(
    principal is Jans::Workload,
    action == Jans::Action::"Read",
    resource is Jans::Resource
)when{
    principal.access_token.org_id == resource.org_id
};"#,
        )
        .with_trusted_issuer("working_issuer", working_issuer_json)
        .with_trusted_issuer("failing_issuer", failing_issuer_json);

    let archive = builder.build_archive().expect("Failed to build archive");
    let temp_dir = extract_archive_to_temp_dir(&archive);

    // Configure Cedarling with JWT validation enabled and async loading
    let config = create_jwt_cedarling_config_with_loader(
        PolicyStoreSource::Directory(temp_dir.path().to_path_buf()),
        true,
        true,
    );

    let cedarling = crate::Cedarling::new(&config)
        .await
        .expect("Cedarling should initialize with JWT-enabled config");

    assert_eq!(
        cedarling.total_issuers(),
        2,
        "Total issuers should be 2 (working and failing)"
    );

    // Poll for loading completion with timeout
    let start = Instant::now();
    let timeout = Duration::from_secs(5);
    loop {
        let loaded = cedarling.loaded_trusted_issuers_count();
        let failed = cedarling.failed_trusted_issuer_ids().len();
        let total = loaded + failed;
        if total == 2 {
            // Both issuers have been processed (one loaded, one failed)
            break;
        }
        assert!(
            (start.elapsed() <= timeout),
            "Timeout waiting for trusted issuers to load. Loaded: {loaded}, Failed: {failed}"
        );
        tokio::time::sleep(Duration::from_millis(1)).await;
    }

    // Test TrustedIssuerLoadingInfo trait methods for mixed results
    // Working issuer should be loaded
    assert!(cedarling.is_trusted_issuer_loaded_by_name("working_issuer"));
    assert!(!cedarling.is_trusted_issuer_loaded_by_name("failing_issuer"));
    assert!(!cedarling.is_trusted_issuer_loaded_by_name("NonExistent"));

    // Check by iss claim
    assert!(cedarling.is_trusted_issuer_loaded_by_iss(working_issuer_url.as_str()));
    assert!(!cedarling.is_trusted_issuer_loaded_by_iss(failing_issuer_url.as_str()));

    // Count and percentage
    assert_eq!(cedarling.loaded_trusted_issuers_count(), 1);
    assert_eq!(cedarling.failed_trusted_issuer_ids().len(), 1);

    // Loaded and failed IDs
    let loaded_ids = cedarling.loaded_trusted_issuer_ids();
    assert_eq!(loaded_ids.len(), 1);
    assert!(loaded_ids.contains("working_issuer"));
    assert!(!loaded_ids.contains("failing_issuer"));

    let failed_ids = cedarling.failed_trusted_issuer_ids();
    assert_eq!(failed_ids.len(), 1);
    assert!(failed_ids.contains("failing_issuer"));
    assert!(!failed_ids.contains("working_issuer"));
}

/// Test that write action is denied for guest users when loaded from directory.
#[test]
#[cfg(not(target_arch = "wasm32"))]
async fn test_load_from_directory_deny_write_for_guest() {
    // Build archive and extract to temp directory
    let builder = create_authz_policy_store_builder();
    let archive = builder
        .build_archive()
        .expect("Failed to build test archive");
    let temp_dir = extract_archive_to_temp_dir(&archive);

    // Create Cedarling from directory
    let cedarling = get_cedarling_from_directory(temp_dir.path().to_path_buf()).await;

    // Create an authorization request for write action with guest user_type
    let request = create_test_unsigned_request(
        "TestApp::Action::\"write\"",
        Some(
            create_test_principal(
                "TestApp::User",
                "guest_user",
                json!({"name": "Guest User", "user_type": "guest"}),
            )
            .expect("Failed to create principal"),
        ),
        create_test_principal(
            "TestApp::Resource",
            "resource1",
            json!({"name": "Test Resource"}),
        )
        .expect("Failed to create resource"),
    );

    // Execute authorization
    let result = cedarling
        .authorize_unsigned(request)
        .await
        .expect("Authorization should succeed");

    // Verify the result - write action should be denied for guest
    assert!(
        !result.decision,
        "Write action should be denied for guest users by the deny-write-guest policy"
    );
}

// ============================================================================
// Archive (.cjar) Loading Tests
// ============================================================================

/// Test that a policy store loaded from a .cjar file works for authorization.
#[test]
#[cfg(not(target_arch = "wasm32"))]
async fn test_load_from_cjar_file_and_authorize_success() {
    // Build archive
    let builder = create_authz_policy_store_builder();
    let archive = builder
        .build_archive()
        .expect("Failed to build test archive");

    // Write archive to temp file
    let temp_dir = TempDir::new().expect("Failed to create temp directory");
    let archive_path = temp_dir.path().join("test_policy_store.cjar");
    fs::write(&archive_path, &archive).expect("Failed to write archive file");

    // Create Cedarling from archive file
    let cedarling = get_cedarling_from_cjar_file(archive_path).await;

    // Create an authorization request
    let request = create_test_unsigned_request(
        "TestApp::Action::\"read\"",
        Some(
            create_test_principal(
                "TestApp::User",
                "user1",
                json!({"name": "Test User", "user_type": "admin"}),
            )
            .expect("Failed to create principal"),
        ),
        create_test_principal(
            "TestApp::Resource",
            "resource1",
            json!({"name": "Test Resource"}),
        )
        .expect("Failed to create resource"),
    );

    // Execute authorization
    let result = cedarling
        .authorize_unsigned(request)
        .await
        .expect("Authorization should succeed");

    // Verify the result
    assert!(
        result.decision,
        "Read action should be allowed by the allow-read policy"
    );
}

/// Test that a single `.cedar` file containing multiple `@id(...)` policies inside a
/// `.cjar` archive loads end-to-end and those policies apply during authorization.
#[test]
#[cfg(not(target_arch = "wasm32"))]
async fn test_load_from_cjar_with_multi_policy_file() {
    // General write permit plus guest-only forbid: without `deny-write-guest`, guests
    // would incorrectly be allowed to write.
    let builder = PolicyStoreTestBuilder::new("a1b2c3d4e5f6a7b8")
        .with_name("Multi-policy cjar test")
        .with_schema(MULTI_POLICY_CJAR_TEST_SCHEMA)
        .with_policy("combined", MULTI_POLICY_COMBINED_CEDAR);

    let archive = builder
        .build_archive()
        .expect("Failed to build test archive");

    let temp_dir = TempDir::new().expect("Failed to create temp directory");
    let archive_path = temp_dir.path().join("multi_policy.cjar");
    fs::write(&archive_path, &archive).expect("Failed to write archive file");

    let cedarling = get_cedarling_from_cjar_file(archive_path).await;

    let admin = |id, name| {
        create_test_principal(
            "TestApp::User",
            id,
            json!({"name": name, "user_type": "admin"}),
        )
        .expect("Failed to create principal")
    };
    let guest = |id, name| {
        create_test_principal(
            "TestApp::User",
            id,
            json!({"name": name, "user_type": "guest"}),
        )
        .expect("Failed to create principal")
    };

    assert!(
        multi_policy_cjar_unsigned_decision(
            &cedarling,
            "TestApp::Action::\"read\"",
            admin("user1", "Test User")
        )
        .await,
        "Read should be allowed by the allow-read policy from the multi-policy file"
    );
    assert!(
        multi_policy_cjar_unsigned_decision(
            &cedarling,
            "TestApp::Action::\"write\"",
            admin("admin_user", "Admin"),
        )
        .await,
        "Write by admin should be explicitly permitted by allow-write-all from the multi-policy file"
    );
    assert!(
        !multi_policy_cjar_unsigned_decision(
            &cedarling,
            "TestApp::Action::\"write\"",
            guest("guest_user", "Guest"),
        )
        .await,
        "Write by guest should be denied by deny-write-guest from the same multi-policy file"
    );
}

/// End-to-end: a `.cjar` archive whose `templates/` contains a single file with
/// two `@id`-annotated Cedar templates must fully round-trip (unpack -> loader
/// -> `PolicySet`) with both templates present in the resulting `PolicySet`.
#[test]
#[cfg(not(target_arch = "wasm32"))]
async fn test_load_from_cjar_with_multi_template_file() {
    let builder = PolicyStoreTestBuilder::new("b1b2b3b4b5b6b7b8")
        .with_name("Multi-template cjar test")
        .with_schema(
            r#"namespace TestApp {
    entity User {
        name: String,
    };
    entity Resource {
        name: String,
    };
    action "view" appliesTo {
        principal: [User],
        resource: [Resource]
    };
}
"#,
        )
        // At least one concrete policy so the store is non-trivial.
        .with_policy(
            "noop",
            r#"@id("noop")
permit(principal, action, resource);"#,
        )
        // One template file with two templates — symmetric to the multi-policy case.
        .with_template(
            "tpls",
            r#"@id("principal-view")
permit(
    principal == ?principal,
    action == TestApp::Action::"view",
    resource
);

@id("resource-view")
permit(
    principal,
    action == TestApp::Action::"view",
    resource == ?resource
);"#,
        );

    let archive = builder
        .build_archive()
        .expect("Failed to build test archive");

    let temp_dir = TempDir::new().expect("Failed to create temp directory");
    let archive_path = temp_dir.path().join("multi_template.cjar");
    fs::write(&archive_path, &archive).expect("Failed to write archive file");

    let http_client = crate::http::HttpClient::new(crate::HttpClientConfig::default())
        .expect("Should create HttpClient");
    let loaded = crate::init::policy_store::load_policy_store(
        &crate::PolicyStoreConfig {
            source: crate::PolicyStoreSource::CjarFile(archive_path),
            ..Default::default()
        },
        &http_client,
        true,
    )
    .await
    .expect("Loading .cjar with a multi-template file should succeed");

    let template_ids: Vec<String> = loaded
        .store
        .policies
        .get_set()
        .templates()
        .map(|t| t.id().to_string())
        .collect();
    assert!(
        template_ids.contains(&"principal-view".to_string())
            && template_ids.contains(&"resource-view".to_string()),
        "expected both template ids in loaded PolicySet, got {template_ids:?}"
    );
}

// ============================================================================
// Policy Store with Entities Tests
// ============================================================================

/// Test loading a policy store with pre-defined entities.
#[test]
#[cfg(not(target_arch = "wasm32"))]
async fn test_load_directory_with_entities() {
    // Build a policy store with entities
    let builder = PolicyStoreTestBuilder::new("e1e2e3e4e5e6e7e8")
        .with_name("Entity Test Policy Store")
        .with_schema(
            r#"namespace TestApp {
    entity User {
        name: String,
        department: String,
    };
    entity Resource {
        name: String,
        owner: String,
    };
    
    action "access" appliesTo {
        principal: [User],
        resource: [Resource]
    };
}
"#,
        )
        .with_policy(
            "allow-same-department",
            r#"@id("allow-same-department")
permit(
    principal,
    action == TestApp::Action::"access",
    resource
);"#,
        )
        .with_entity(
            "users",
            serde_json::to_string(&json!([
                {
                    "uid": {"type": "TestApp::User", "id": "alice"},
                    "attrs": {
                        "name": "Alice",
                        "department": "engineering"
                    },
                    "parents": []
                }
            ]))
            .unwrap(),
        )
        .with_entity(
            "resources",
            serde_json::to_string(&json!([
                {
                    "uid": {"type": "TestApp::Resource", "id": "doc1"},
                    "attrs": {
                        "name": "Design Document",
                        "owner": "engineering"
                    },
                    "parents": []
                }
            ]))
            .unwrap(),
        );

    let archive = builder
        .build_archive()
        .expect("Failed to build test archive");
    let temp_dir = extract_archive_to_temp_dir(&archive);

    // Create Cedarling from directory
    let cedarling = get_cedarling_from_directory(temp_dir.path().to_path_buf()).await;

    // Create an authorization request
    let request = create_test_unsigned_request(
        "TestApp::Action::\"access\"",
        Some(
            create_test_principal(
                "TestApp::User",
                "alice",
                json!({"name": "Alice", "department": "engineering"}),
            )
            .expect("Failed to create principal"),
        ),
        create_test_principal(
            "TestApp::Resource",
            "doc1",
            json!({"name": "Design Document", "owner": "engineering"}),
        )
        .expect("Failed to create resource"),
    );

    // Execute authorization
    let result = cedarling
        .authorize_unsigned(request)
        .await
        .expect("Authorization should succeed");

    // Verify the result
    assert!(
        result.decision,
        "Access should be allowed by the allow-same-department policy"
    );
}

// ============================================================================
// Multiple Policies Tests
// ============================================================================
fn create_multiple_policy_store_builder() -> PolicyStoreTestBuilder {
    PolicyStoreTestBuilder::new("f1f2f3f4f5f6f7f8")
        .with_name("Multi-Policy Test Store")
        .with_schema(
            r#"namespace TestApp {
    entity User {
        user_role: String,
    };
    entity Resource;
    
    action "read" appliesTo {
        principal: [User],
        resource: [Resource]
    };
    
    action "write" appliesTo {
        principal: [User],
        resource: [Resource]
    };
    
    action "delete" appliesTo {
        principal: [User],
        resource: [Resource]
    };
}
"#,
        )
        .with_policy(
            "allow-read-all",
            r#"@id("allow-read-all")
permit(
    principal,
    action == TestApp::Action::"read",
    resource
);"#,
        )
        .with_policy(
            "allow-write-admin",
            r#"@id("allow-write-admin")
permit(
    principal,
    action == TestApp::Action::"write",
    resource
) when { principal.user_role == "admin" };"#,
        )
        .with_policy(
            "deny-delete-all",
            r#"@id("deny-delete-all")
forbid(
    principal,
    action == TestApp::Action::"delete",
    resource
);"#,
        )
}
/// Test loading a policy store with multiple policies and verifying correct policy evaluation.
#[test]
#[cfg(not(target_arch = "wasm32"))]
async fn test_load_directory_with_multiple_policies() {
    // Build a policy store with multiple policies
    let builder = create_multiple_policy_store_builder();

    let archive = builder
        .build_archive()
        .expect("Failed to build test archive");
    let temp_dir = extract_archive_to_temp_dir(&archive);

    // Create Cedarling from directory
    let cedarling = get_cedarling_from_directory(temp_dir.path().to_path_buf()).await;

    // Test 1: Read should be allowed for any user
    let read_request = create_test_unsigned_request(
        "TestApp::Action::\"read\"",
        Some(
            create_test_principal("TestApp::User", "user1", json!({"user_role": "viewer"}))
                .expect("Failed to create principal"),
        ),
        create_test_principal("TestApp::Resource", "resource1", json!({}))
            .expect("Failed to create resource"),
    );

    let read_result = cedarling
        .authorize_unsigned(read_request)
        .await
        .expect("Read authorization should succeed");

    assert!(read_result.decision, "Read should be allowed for any user");

    // Test 2: Write should be allowed only for admin
    let write_admin_request = create_test_unsigned_request(
        "TestApp::Action::\"write\"",
        Some(
            create_test_principal("TestApp::User", "admin1", json!({"user_role": "admin"}))
                .expect("Failed to create principal"),
        ),
        create_test_principal("TestApp::Resource", "resource1", json!({}))
            .expect("Failed to create resource"),
    );

    let write_admin_result = cedarling
        .authorize_unsigned(write_admin_request)
        .await
        .expect("Write authorization should succeed");

    assert!(
        write_admin_result.decision,
        "Write should be allowed for admin"
    );

    // Test 3: Write should be denied for non-admin
    let write_viewer_request = create_test_unsigned_request(
        "TestApp::Action::\"write\"",
        Some(
            create_test_principal("TestApp::User", "user1", json!({"user_role": "viewer"}))
                .expect("Failed to create principal"),
        ),
        create_test_principal("TestApp::Resource", "resource1", json!({}))
            .expect("Failed to create resource"),
    );

    let write_viewer_result = cedarling
        .authorize_unsigned(write_viewer_request)
        .await
        .expect("Write authorization should succeed");

    assert!(
        !write_viewer_result.decision,
        "Write should be denied for non-admin"
    );

    // Test 4: Delete should be denied for everyone
    let delete_request = create_test_unsigned_request(
        "TestApp::Action::\"delete\"",
        Some(
            create_test_principal("TestApp::User", "admin1", json!({"user_role": "admin"}))
                .expect("Failed to create principal"),
        ),
        create_test_principal("TestApp::Resource", "resource1", json!({}))
            .expect("Failed to create resource"),
    );

    let delete_result = cedarling
        .authorize_unsigned(delete_request)
        .await
        .expect("Delete authorization should succeed");

    assert!(
        !delete_result.decision,
        "Delete should be denied for everyone"
    );
}

// ============================================================================
// Archive URL Tests (WASM-Compatible via CjarUrl)
// ============================================================================

/// Test loading a policy store from a URL using mockito.
///
/// This test is WASM-compatible as it uses HTTP to fetch the archive,
/// which works in both native and WASM environments.
#[test]
async fn test_load_from_cjar_url_and_authorize_success() {
    use mockito::Server;

    // Build archive bytes
    let builder = create_authz_policy_store_builder();
    let archive_bytes = builder
        .build_archive()
        .expect("Failed to build test archive");

    // Create mock server
    let mut server = Server::new_async().await;
    let mock = server
        .mock("GET", "/policy-store.cjar")
        .with_status(200)
        .with_header("content-type", "application/octet-stream")
        .with_body(archive_bytes)
        .create_async()
        .await;

    let cjar_url = format!("{}/policy-store.cjar", server.url());

    // Create Cedarling from CjarUrl
    let cedarling = get_cedarling_with_callback(PolicyStoreSource::CjarUrl(cjar_url), |_| {}).await;

    // Verify the mock was called
    mock.assert_async().await;

    // Create an authorization request
    let request = create_test_unsigned_request(
        "TestApp::Action::\"read\"",
        Some(
            create_test_principal(
                "TestApp::User",
                "user1",
                json!({"name": "Test User", "user_type": "admin"}),
            )
            .expect("Failed to create principal"),
        ),
        create_test_principal(
            "TestApp::Resource",
            "resource1",
            json!({"name": "Test Resource"}),
        )
        .expect("Failed to create resource"),
    );

    // Execute authorization
    let result = cedarling
        .authorize_unsigned(request)
        .await
        .expect("Authorization should succeed");

    // Verify the result
    assert!(
        result.decision,
        "Read action should be allowed when loading from CjarUrl"
    );
}

/// Test that `CjarUrl` handles HTTP errors gracefully.
/// The HTTP client retries on HTTP error status codes before failing.
#[test]
async fn test_cjar_url_handles_http_error() {
    use super::utils::cedarling_util::get_config;
    use mockito::Server;

    // Create mock server that returns 404
    // Note: The HTTP client will retry on HTTP errors, so expect multiple requests
    let mut server = Server::new_async().await;
    let mock = server
        .mock("GET", "/nonexistent.cjar")
        .with_status(404)
        .with_body("Not Found")
        .expect_at_least(1)
        .create_async()
        .await;

    let cjar_url = format!("{}/nonexistent.cjar", server.url());

    // Attempt to create Cedarling - should fail after retries
    let config = get_config(PolicyStoreSource::CjarUrl(cjar_url));

    let err = Cedarling::new(&config)
        .await
        .err()
        .expect("Cedarling initialization should fail after retries on 404 error");

    // Verify the mock was called at least once
    mock.assert_async().await;

    // Verify the error is an Archive error (max retries exceeded after HTTP errors)
    assert!(
        matches!(
            &err,
            crate::InitCedarlingError::ServiceConfig(
                crate::init::service_config::ServiceConfigError::PolicyStore(
                    crate::init::policy_store::PolicyStoreLoadError::Archive(_)
                )
            )
        ),
        "Expected Archive error after retries, got: {err:?}"
    );
}

/// Test loading archive from bytes directly using the loader function.
///
/// This tests the `load_policy_store_archive_bytes` function which is the
/// underlying mechanism used by `CjarUrl` and is WASM-compatible.
#[test]
async fn test_load_policy_store_archive_bytes_directly() {
    use crate::common::policy_store::loader::load_policy_store_archive_bytes;

    // Build archive bytes
    let builder = create_authz_policy_store_builder();
    let archive_bytes = builder
        .build_archive()
        .expect("Failed to build test archive");

    // Load directly using the bytes loader
    let loaded = load_policy_store_archive_bytes(&archive_bytes, true)
        .expect("Should load policy store from bytes");

    // Verify the loaded policy store
    assert_eq!(
        loaded.metadata.policy_store.id, "a1b2c3d4e5f6a7b8",
        "Policy store ID should match"
    );
    assert_eq!(
        loaded.metadata.policy_store.name, "Integration Test Policy Store",
        "Policy store name should match"
    );
    assert!(
        !loaded.policies.is_empty(),
        "Should have loaded at least one policy"
    );
    assert_eq!(loaded.policies.len(), 2, "Should have loaded 2 policies");

    // Verify policy content
    let policy_names: Vec<&str> = loaded.policies.iter().map(|p| p.name.as_str()).collect();
    assert!(
        policy_names.contains(&"allow-read.cedar"),
        "Should have allow-read policy"
    );
    assert!(
        policy_names.contains(&"deny-write-guest.cedar"),
        "Should have deny-write-guest policy"
    );
}

/// Test that invalid archive bytes are rejected.
#[test]
async fn test_load_policy_store_archive_bytes_invalid() {
    use crate::common::policy_store::loader::load_policy_store_archive_bytes;

    // Try to load invalid bytes
    let invalid_bytes = vec![0x00, 0x01, 0x02, 0x03];
    let err = load_policy_store_archive_bytes(&invalid_bytes, true)
        .expect_err("Should fail to load invalid archive bytes");

    // Verify the error is an Archive error (invalid zip format)
    assert!(
        matches!(
            err,
            crate::common::policy_store::errors::PolicyStoreError::Archive(_)
        ),
        "Expected Archive error for invalid bytes, got: {err:?}"
    );
}

#[test]
async fn test_load_from_uri_detects_archive() {
    use mockito::Server;

    let builder = create_authz_policy_store_builder();
    let archive_bytes = builder
        .build_archive()
        .expect("Failed to build test archive");

    let mut server = Server::new_async().await;
    let mock = server
        .mock("GET", "/policy-store")
        .with_status(200)
        .with_header("content-type", "application/octet-stream")
        .with_body(archive_bytes)
        .create_async()
        .await;

    let uri = format!("{}/policy-store", server.url());
    let cedarling = get_cedarling_with_callback(PolicyStoreSource::Uri(uri), |_| {}).await;

    mock.assert_async().await;

    let request = create_test_unsigned_request(
        "TestApp::Action::\"read\"",
        Some(
            create_test_principal(
                "TestApp::User",
                "user1",
                json!({"name": "Test User", "user_type": "admin"}),
            )
            .expect("Failed to create principal"),
        ),
        create_test_principal(
            "TestApp::Resource",
            "resource1",
            json!({"name": "Test Resource"}),
        )
        .expect("Failed to create resource"),
    );

    let result = cedarling
        .authorize_unsigned(request)
        .await
        .expect("Authorization should succeed");

    assert!(
        result.decision,
        "Read action should be allowed when loading archive via Uri"
    );
}

// ============================================================================
// No-Schema / Strict Validation Tests
// ============================================================================

/// Helper: build a `.cjar` archive without a schema file (only metadata + policies).
fn build_archive_without_schema(id: &str, name: &str) -> Vec<u8> {
    // ID must be valid hex 8-64 chars
    assert!(
        id.len() >= 8 && id.len() <= 64 && id.chars().all(|c| c.is_ascii_hexdigit()),
        "test archive id must be hex 8-64 chars, got: {id}"
    );
    let mut buf = Vec::new();
    {
        let cursor = std::io::Cursor::new(&mut buf);
        let mut zip = zip::ZipWriter::new(cursor);
        let opts = <zip::write::FileOptions<zip::write::ExtendedFileOptions>>::default()
            .compression_method(zip::CompressionMethod::Deflated);

        zip.start_file("metadata.json", opts.clone()).unwrap();
        write!(
            zip,
            r#"{{"cedar_version":"4.4.0","policy_store":{{"id":"{id}","name":"{name}","version":"1.0.0"}}}}"#
        )
        .unwrap();

        zip.start_file("policies/allow.cedar", opts).unwrap();
        zip.write_all(b"@id(\"allow-all\")\npermit(principal, action, resource);")
            .unwrap();

        zip.finish().unwrap();
    }
    buf
}

/// Directory without a schema + strict=false should succeed (schemaless mode).
#[test]
#[cfg(not(target_arch = "wasm32"))]
async fn test_load_directory_without_schema_strict_false_succeeds() {
    let archive = build_archive_without_schema("deadbeef12345678", "No Schema Dir");
    let temp_dir = extract_archive_to_temp_dir(&archive);

    let cedarling = get_cedarling_with_callback(
        PolicyStoreSource::Directory(temp_dir.path().to_path_buf()),
        |config| {
            config.authorization_config.strict_schema_validation = false;
        },
    )
    .await;

    let request = create_test_unsigned_request(
        "TestApp::Action::\"read\"",
        Some(
            create_test_principal("TestApp::User", "user1", json!({"name": "Test User"}))
                .expect("principal should build"),
        ),
        create_test_principal("TestApp::Resource", "res1", json!({}))
            .expect("resource should build"),
    );

    let result = cedarling
        .authorize_unsigned(request)
        .await
        .expect("authorization should succeed without schema");
    assert!(result.decision, "allow-all should permit");
}

/// Directory without a schema + strict=true should fail init.
#[test]
#[cfg(not(target_arch = "wasm32"))]
async fn test_load_directory_without_schema_strict_true_fails() {
    let archive = build_archive_without_schema("deadbeef87654321", "No Schema Dir Strict");
    let temp_dir = extract_archive_to_temp_dir(&archive);

    let mut config = get_config(PolicyStoreSource::Directory(temp_dir.path().to_path_buf()));
    config.authorization_config.strict_schema_validation = true;

    let result = Cedarling::new(&config).await;
    assert!(
        result.is_err(),
        "Expected init to fail: strict_schema_validation=true but policy store has no schema (directory)"
    );
}

/// Archive without a schema + strict=false should succeed (schemaless mode).
#[test]
async fn test_archive_without_schema_strict_false_succeeds() {
    let archive_bytes = build_archive_without_schema("deadbeefaaaabbbb", "No Schema Archive");

    let cedarling =
        get_cedarling_with_callback(PolicyStoreSource::ArchiveBytes(archive_bytes), |config| {
            config.authorization_config.strict_schema_validation = false;
        })
        .await;

    let request = create_test_unsigned_request(
        "TestApp::Action::\"read\"",
        Some(
            create_test_principal("TestApp::User", "user1", json!({"name": "Test User"}))
                .expect("principal should build"),
        ),
        create_test_principal("TestApp::Resource", "res1", json!({}))
            .expect("resource should build"),
    );

    let result = cedarling
        .authorize_unsigned(request)
        .await
        .expect("authorization should succeed without schema");
    assert!(result.decision, "allow-all should permit");
}