treetop-core 0.0.23

Core library for Treetop, a Cedar policy engine implementation.
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
use cedar_policy::{
    Authorizer, Entities, Entity, Policy, PolicyId, PolicySet, Request as CedarRequest, Schema,
};
use std::collections::{HashMap, HashSet};
use std::sync::{Arc, OnceLock};
use std::time::{Duration, Instant, SystemTime};
use std::vec;

use crate::labels::LabelRegistry;
use crate::policy_match::{
    action_match_reason, matches_effect, principal_match_reason, resource_match_reason,
};
use crate::policy_store::{
    ExplicitPolicyStore, PolicyStoreId, PolicyStoreLayout, display_policy_id,
};
use crate::query::{ActionQuery, PrincipalQuery, ResourceQuery};
use crate::timers::PhaseTimer;
use crate::traits::CedarAtom;
use crate::types::{
    Decision, DecisionDiagnostics, FromDecisionWithPolicy, PermitPolicies, PermitPolicy,
    PolicyEffectFilter, PolicyMatchReason, PolicyVersion, Request, RequestContext, Resource,
    UserPolicies,
};
use crate::{Groups, Principal};
use crate::{error::PolicyError, loader};
use arc_swap::ArcSwap;

use sha2::{Digest, Sha256};
use tracing::debug;
#[cfg(feature = "observability")]
use tracing::info_span;

#[cfg(feature = "observability")]
use crate::metrics::{
    EvaluationObservation, EvaluationPhases, MatchedPolicySource, get_sink, metrics_enabled,
    record_evaluation_observation, record_reload,
};

/// Static cached Authorizer instance (stateless, reusable across evaluations).
fn get_authorizer() -> &'static Authorizer {
    static AUTHORIZER: OnceLock<Authorizer> = OnceLock::new();
    AUTHORIZER.get_or_init(Authorizer::new)
}

/// Aggregates timing information for all evaluation phases.
#[derive(Debug)]
struct EvalTimers {
    /// Total elapsed time from start of evaluation
    total_start: Option<Instant>,
    /// Whether individual phase timers should sample the clock.
    measure_enabled: bool,
    /// Whether debug tracing was enabled when evaluation started.
    debug_enabled: bool,
    /// Time spent applying labels
    labels: Duration,
    /// Time spent constructing Cedar request
    construct_req: Duration,
    /// Time spent building Cedar entities
    entities: Duration,
    /// Time spent resolving groups
    groups: Duration,
    /// Time spent performing authorization
    authz: Duration,
}

impl EvalTimers {
    fn start(measure_enabled: bool, debug_enabled: bool) -> Self {
        Self {
            total_start: measure_enabled.then(Instant::now),
            measure_enabled,
            debug_enabled,
            labels: Duration::ZERO,
            construct_req: Duration::ZERO,
            entities: Duration::ZERO,
            groups: Duration::ZERO,
            authz: Duration::ZERO,
        }
    }

    fn total_elapsed(&self) -> Duration {
        self.total_start
            .map_or(Duration::ZERO, |start| start.elapsed())
    }
}

/// Result of preparing a request for authorization: Cedar request, entities, snapshot, and phase timings.
struct PreparedRequest {
    cedar_req: CedarRequest,
    entities: Entities,
    snapshot: Snapshot,
    selected_store: Option<usize>,
    timers: EvalTimers,
    #[cfg(feature = "observability")]
    sink: crate::metrics::SinkGuard,
    #[cfg(feature = "observability")]
    metrics_enabled: bool,
}

/// Compiled authorization policy sets for a monolithic or partitioned engine.
#[derive(Debug)]
enum PolicySets {
    Monolithic(Box<PolicySet>),
    Scoped {
        layout: PolicyStoreLayout,
        stores: Vec<PolicySet>,
    },
}

enum PolicySetIter<'a> {
    Monolithic(std::iter::Once<&'a PolicySet>),
    Scoped(std::slice::Iter<'a, PolicySet>),
}

impl<'a> Iterator for PolicySetIter<'a> {
    type Item = &'a PolicySet;

    fn next(&mut self) -> Option<Self::Item> {
        match self {
            Self::Monolithic(iter) => iter.next(),
            Self::Scoped(iter) => iter.next(),
        }
    }
}

impl PolicySets {
    fn layout(&self) -> Option<&PolicyStoreLayout> {
        match self {
            Self::Monolithic(_) => None,
            Self::Scoped { layout, .. } => Some(layout),
        }
    }

    fn resolve_store(&self, request: &Request) -> Result<Option<usize>, PolicyError> {
        match self {
            Self::Monolithic(_) => Ok(None),
            Self::Scoped { layout, .. } => layout
                .resolve_request(&request.action, &request.resource)
                .map(Some),
        }
    }

    fn selected(&self, store: Option<usize>) -> Result<&PolicySet, PolicyError> {
        match (self, store) {
            (Self::Monolithic(set), None) => Ok(set),
            (Self::Scoped { layout, stores }, Some(index)) => stores.get(index).ok_or_else(|| {
                PolicyError::PolicyStoreRoutingError(format!(
                    "configured policy-store index {index} is outside layout length {}",
                    layout.stores().len()
                ))
            }),
            (Self::Monolithic(_), Some(index)) => Err(PolicyError::PolicyStoreRoutingError(
                format!("monolithic engine was given policy-store index {index}"),
            )),
            (Self::Scoped { .. }, None) => Err(PolicyError::PolicyStoreRoutingError(
                "partitioned engine did not resolve a policy store".to_string(),
            )),
        }
    }

    fn iter(&self) -> PolicySetIter<'_> {
        match self {
            Self::Monolithic(set) => PolicySetIter::Monolithic(std::iter::once(set)),
            Self::Scoped { stores, .. } => PolicySetIter::Scoped(stores.iter()),
        }
    }

    fn store_ids(&self) -> Option<Vec<PolicyStoreId>> {
        let Self::Scoped { layout, .. } = self else {
            return None;
        };
        Some(
            layout
                .stores()
                .iter()
                .map(|store| store.id().clone())
                .collect(),
        )
    }
}

/// Immutable snapshot of compiled policy sets, along with metadata.
#[derive(Debug)]
struct PolicySnapshot {
    sets: PolicySets,
    version: PolicyVersion,
    permit_policies: HashMap<PolicyId, PermitPolicy>,
    forbid_policy_ids: HashMap<PolicyId, String>,
    schema: Option<Arc<Schema>>,
}

/// Convenience alias for a shared policy snapshot.
type Snapshot = Arc<PolicySnapshot>;

impl PolicySnapshot {
    fn from_policy_text(policy_text: &str) -> Result<Self, PolicyError> {
        Self::from_policy_text_with_schema_and_stores(policy_text, None, None)
    }

    fn from_policy_text_with_schema(
        policy_text: &str,
        schema: Option<Arc<Schema>>,
    ) -> Result<Self, PolicyError> {
        Self::from_policy_text_with_schema_and_stores(policy_text, schema, None)
    }

    fn from_policy_text_with_schema_and_stores(
        policy_text: &str,
        schema: Option<Arc<Schema>>,
        layout: Option<PolicyStoreLayout>,
    ) -> Result<Self, PolicyError> {
        let set = match schema.as_deref() {
            Some(schema) => loader::compile_policy_with_schema(policy_text, schema)?,
            None => loader::compile_policy(policy_text)?,
        };
        let permit_policies = loader::precompute_permit_policies(&set)?;
        let forbid_policy_ids = loader::precompute_forbid_policy_ids(&set);
        let sets = match layout {
            Some(layout) => partition_policy_set(&set, layout)?,
            None => PolicySets::Monolithic(Box::new(set)),
        };

        let mut hasher = Sha256::new();
        hasher.update(policy_text.as_bytes());
        let digest = hasher.finalize();
        let mut hash = String::with_capacity(digest.len() * 2);
        const HEX: &[u8; 16] = b"0123456789abcdef";
        for byte in digest {
            hash.push(char::from(HEX[usize::from(byte >> 4)]));
            hash.push(char::from(HEX[usize::from(byte & 0x0f)]));
        }

        Ok(PolicySnapshot {
            sets,
            version: PolicyVersion {
                hash: hash.into(),
                loaded_at: humantime::format_rfc3339(SystemTime::now())
                    .to_string()
                    .into(),
            },
            permit_policies,
            forbid_policy_ids,
            schema,
        })
    }

    fn version(&self) -> PolicyVersion {
        self.version.clone()
    }

    fn schema(&self) -> Option<&Schema> {
        self.schema.as_deref()
    }
}

fn partition_policy_set(
    source: &PolicySet,
    layout: PolicyStoreLayout,
) -> Result<PolicySets, PolicyError> {
    let mut stores = (0..layout.stores().len())
        .map(|_| PolicySet::new())
        .collect::<Vec<_>>();
    let mut found_global_policy_ids = HashSet::new();

    for policy in source.policies() {
        let display_id = display_policy_id(policy);
        let registered_global = policy
            .annotation("id")
            .is_some_and(|id| layout.global_policy_ids().contains(id));
        if registered_global {
            found_global_policy_ids.insert(display_id.to_string());
        }

        let explicit = layout.explicit_policy_store(policy)?;
        if registered_global
            && let Some(ExplicitPolicyStore::Store(store_index)) = explicit.as_ref()
        {
            return Err(PolicyError::PolicyStoreConfigError(format!(
                "policy '{display_id}' is registered as global but @{POLICY_STORE_ANNOTATION} assigns it to store '{}'",
                layout.stores()[*store_index].id(),
                POLICY_STORE_ANNOTATION = crate::POLICY_STORE_ANNOTATION
            )));
        }
        let target_indexes = if registered_global
            || matches!(explicit, Some(ExplicitPolicyStore::Global))
        {
            (0..layout.stores().len()).collect::<Vec<_>>()
        } else {
            let candidates = layout.policy_candidates(policy)?;
            match explicit {
                Some(ExplicitPolicyStore::Store(store_index)) => {
                    if candidates
                        .first()
                        .is_some_and(|candidate| *candidate != store_index)
                    {
                        return Err(PolicyError::PolicyStoreConfigError(format!(
                            "policy '{display_id}' is assigned to store '{}' but its scope identifies store '{}'",
                            layout.stores()[store_index].id(),
                            layout.stores()[candidates[0]].id()
                        )));
                    }
                    vec![store_index]
                }
                None => match candidates.as_slice() {
                    [store_index] => vec![*store_index],
                    [] => {
                        return Err(PolicyError::PolicyStoreConfigError(format!(
                            "policy '{display_id}' cannot be assigned from its configured namespace references; add @{POLICY_STORE_ANNOTATION}(\"store-id\") or mark it global",
                            POLICY_STORE_ANNOTATION = crate::POLICY_STORE_ANNOTATION
                        )));
                    }
                    _ => {
                        return Err(PolicyError::PolicyStoreConfigError(format!(
                            "policy '{display_id}' has an ambiguous policy-store assignment"
                        )));
                    }
                },
                Some(ExplicitPolicyStore::Global) => {
                    return Err(PolicyError::PolicyStoreConfigError(format!(
                        "policy '{display_id}' has an inconsistent global assignment"
                    )));
                }
            }
        };

        for target_index in target_indexes {
            let target_id = layout.stores()[target_index].id();
            let target = stores.get_mut(target_index).ok_or_else(|| {
                PolicyError::PolicyStoreConfigError(format!(
                    "policy '{display_id}' resolved to missing store '{target_id}'"
                ))
            })?;
            target.add(policy.clone()).map_err(|error| {
                PolicyError::PolicyStoreConfigError(format!(
                    "failed to add policy '{display_id}' to store '{target_id}': {error}"
                ))
            })?;
        }
    }

    let mut missing_global_policy_ids = layout
        .global_policy_ids()
        .difference(&found_global_policy_ids)
        .cloned()
        .collect::<Vec<_>>();
    if !missing_global_policy_ids.is_empty() {
        missing_global_policy_ids.sort();
        return Err(PolicyError::PolicyStoreConfigError(format!(
            "global policy IDs were not found in the policy source: {}",
            missing_global_policy_ids.join(", ")
        )));
    }

    Ok(PolicySets::Scoped { layout, stores })
}

/// Extract all permit policies from the Cedar authorization result.
#[inline]
fn extract_permit_policies(
    snapshot: &PolicySnapshot,
    result: &cedar_policy::Response,
) -> PermitPolicies {
    if result.decision() != cedar_policy::Decision::Allow {
        return PermitPolicies::empty();
    }

    result
        .diagnostics()
        .reason()
        .filter_map(|reason| snapshot.permit_policies.get(reason))
        .cloned()
        .collect()
}

/// Extract matched forbid policy IDs from a Cedar authorization result.
#[inline]
fn extract_forbid_policy_ids(
    snapshot: &PolicySnapshot,
    result: &cedar_policy::Response,
) -> Vec<String> {
    if result.decision() != cedar_policy::Decision::Deny {
        return Vec::new();
    }

    let mut ids: Vec<String> = result
        .diagnostics()
        .reason()
        .filter_map(|reason| snapshot.forbid_policy_ids.get(reason).cloned())
        .collect();
    ids.sort();
    ids.dedup();
    ids
}

/// Iterate over groups from a request principal.
#[inline]
fn request_groups(request: &Request) -> Option<&Groups> {
    match &request.principal {
        Principal::User(user) => Some(user.groups()),
        Principal::Group(_) => None,
    }
}

/// Apply label augmentations to a resource.
#[inline]
fn apply_labels(
    registry: &LabelRegistry,
    resource: &crate::types::Resource,
    timers: &mut EvalTimers,
) -> Option<crate::types::Resource> {
    let measure_enabled = timers.measure_enabled;
    let _timer = PhaseTimer::new_if(&mut timers.labels, measure_enabled);
    #[cfg(feature = "observability")]
    let _label_span = info_span!("apply_labels").entered();
    registry.apply_to_clone_if_applicable(resource)
}

/// Build the Cedar request context from the optional typed context.
#[inline]
fn build_effective_context(
    request_context: Option<&RequestContext>,
) -> Result<cedar_policy::Context, PolicyError> {
    match request_context {
        Some(context) if !context.is_empty() => context.to_cedar_context(),
        _ => Ok(cedar_policy::Context::empty()),
    }
}

/// Build a Cedar request from the authorization request and resource.
/// UIDs should be pre-converted to avoid redundant conversions.
#[inline]
fn build_cedar_req(
    principal_uid: cedar_policy::EntityUid,
    action_uid: cedar_policy::EntityUid,
    resource_uid: cedar_policy::EntityUid,
    context: cedar_policy::Context,
    schema: Option<&Schema>,
    timers: &mut EvalTimers,
) -> Result<CedarRequest, PolicyError> {
    let measure_enabled = timers.measure_enabled;
    let _timer = PhaseTimer::new_if(&mut timers.construct_req, measure_enabled);
    #[cfg(feature = "observability")]
    let _req_span = info_span!("construct_cedar_req").entered();

    Ok(CedarRequest::new(
        principal_uid,
        action_uid,
        resource_uid,
        context,
        schema,
    )?)
}

/// Build Cedar entities for the principal, resource, and groups.
/// UIDs should be pre-converted to avoid redundant conversions.
#[inline]
fn build_entities(
    principal_uid: cedar_policy::EntityUid,
    resource_uid: cedar_policy::EntityUid,
    resource: &crate::types::Resource,
    groups: Option<&Groups>,
    schema: Option<&Schema>,
    timers: &mut EvalTimers,
) -> Result<Entities, PolicyError> {
    let group_uids = {
        let measure_enabled = timers.measure_enabled;
        let _timer = PhaseTimer::new_if(&mut timers.groups, measure_enabled);
        #[cfg(feature = "observability")]
        let _groups_span = info_span!("resolve_groups").entered();

        let mut group_uids = HashSet::with_capacity(groups.map_or(0, Groups::len));
        if let Some(groups) = groups {
            for group in groups {
                group_uids.insert(group.cedar_entity_uid()?);
            }
        }
        group_uids
    };

    // Group resolution is deliberately measured outside this phase so phase
    // totals are non-overlapping.
    let entities = {
        let measure_enabled = timers.measure_enabled;
        let _timer = PhaseTimer::new_if(&mut timers.entities, measure_enabled);
        #[cfg(feature = "observability")]
        let _entity_span = info_span!("construct_entities").entered();

        // Construct resource entity
        let resource_attrs = resource.cedar_attr()?;
        let resource_entity =
            cedar_policy::Entity::new(resource_uid, resource_attrs, Default::default())?;

        // Construct group entities before moving the parent set into the
        // principal. This avoids cloning the complete HashSet allocation.
        let mut all_entities = Vec::with_capacity(group_uids.len() + 2);
        all_entities.extend(group_uids.iter().cloned().map(Entity::with_uid));

        // Construct principal entity with groups as parents, then batch all
        // entities into a single call. Entity order has no Cedar semantics.
        let principal_entity = Entity::new(principal_uid, HashMap::new(), group_uids)?;
        all_entities.push(principal_entity);
        all_entities.push(resource_entity);

        // Combine all entities in a single call to reduce overhead
        Entities::empty().add_entities(all_entities, schema)?
    };

    if timers.debug_enabled {
        debug!(
            event = "Request",
            phase = "Entities",
            time = timers.entities.as_micros(),
            entity_count = entities.iter().count()
        );
    }

    Ok(entities)
}

/// The main engine handle. Thread-safe and cheaply cloneable.
///
/// Cloning is cheap (just increments Arc refcounts), but for multithreaded
/// applications, wrapping in `Arc<PolicyEngine>` and using `Arc::clone()`
/// is more idiomatic and makes ownership clearer.
///
/// For single-threaded use or when passing the engine to a single thread,
/// you can simply clone it directly.
#[derive(Clone)]
pub struct PolicyEngine {
    /// Shared pointer to an `ArcSwap` holding the current policy snapshot.
    inner: Arc<ArcSwap<PolicySnapshot>>,
    /// Optional label registry for augmenting resources with derived attributes.
    label_registry: Option<Arc<LabelRegistry>>,
}

impl From<PolicyEngine> for PolicyVersion {
    fn from(engine: PolicyEngine) -> Self {
        engine.current_version()
    }
}

impl From<&PolicyEngine> for PolicyVersion {
    fn from(engine: &PolicyEngine) -> Self {
        engine.current_version()
    }
}

impl PolicyEngine {
    fn from_snapshot(snapshot: PolicySnapshot) -> Self {
        Self {
            inner: Arc::new(ArcSwap::from(Arc::new(snapshot))),
            label_registry: None,
        }
    }

    pub fn new_from_str(policy_text: &str) -> Result<Self, PolicyError> {
        Ok(Self::from_snapshot(PolicySnapshot::from_policy_text(
            policy_text,
        )?))
    }

    /// Create an engine that partitions policies into namespace-owned stores.
    ///
    /// Existing monolithic constructors remain unchanged. Store assignment is
    /// validated before the engine is returned, and each request must resolve
    /// to exactly one declared store or evaluation fails closed.
    pub fn new_from_str_with_policy_stores(
        policy_text: &str,
        layout: PolicyStoreLayout,
    ) -> Result<Self, PolicyError> {
        Ok(Self::from_snapshot(
            PolicySnapshot::from_policy_text_with_schema_and_stores(
                policy_text,
                None,
                Some(layout),
            )?,
        ))
    }

    /// Create a new policy engine with schema-based policy and request validation.
    pub fn new_from_str_with_schema(
        policy_text: &str,
        schema: Schema,
    ) -> Result<Self, PolicyError> {
        Ok(Self::from_snapshot(
            PolicySnapshot::from_policy_text_with_schema(policy_text, Some(Arc::new(schema)))?,
        ))
    }

    /// Create a namespace-partitioned engine with schema validation.
    pub fn new_from_str_with_schema_and_policy_stores(
        policy_text: &str,
        schema: Schema,
        layout: PolicyStoreLayout,
    ) -> Result<Self, PolicyError> {
        Ok(Self::from_snapshot(
            PolicySnapshot::from_policy_text_with_schema_and_stores(
                policy_text,
                Some(Arc::new(schema)),
                Some(layout),
            )?,
        ))
    }

    /// Create a new policy engine from policy text and Cedar schema text.
    pub fn new_from_str_with_cedarschema(
        policy_text: &str,
        schema_text: &str,
    ) -> Result<Self, PolicyError> {
        let schema: Schema = schema_text
            .parse()
            .map_err(|e| PolicyError::ParseError(format!("failed to parse Cedar schema: {e}")))?;
        Self::new_from_str_with_schema(policy_text, schema)
    }

    /// Create a namespace-partitioned engine from policy and Cedar schema text.
    pub fn new_from_str_with_cedarschema_and_policy_stores(
        policy_text: &str,
        schema_text: &str,
        layout: PolicyStoreLayout,
    ) -> Result<Self, PolicyError> {
        let schema: Schema = schema_text
            .parse()
            .map_err(|e| PolicyError::ParseError(format!("failed to parse Cedar schema: {e}")))?;
        Self::new_from_str_with_schema_and_policy_stores(policy_text, schema, layout)
    }

    /// Create a new policy engine with a label registry.
    ///
    /// This is a convenience method that combines `new_from_str` and `with_label_registry`.
    pub fn with_label_registry(mut self, registry: LabelRegistry) -> Self {
        self.label_registry = Some(Arc::new(registry));
        self
    }

    /// Set or replace the label registry for this engine.
    ///
    /// This allows updating the labelers after the engine has been created.
    pub fn set_label_registry(&mut self, registry: LabelRegistry) {
        self.label_registry = Some(Arc::new(registry));
    }

    /// Get a reference to the label registry, if one is configured.
    pub fn label_registry(&self) -> Option<&LabelRegistry> {
        self.label_registry.as_deref()
    }

    pub fn reload_from_str(&self, policy_text: &str) -> Result<(), PolicyError> {
        let current_snapshot = self.current_snapshot();
        let had_schema = current_snapshot.schema.is_some();
        let schema = current_snapshot.schema.clone();
        let layout = current_snapshot.sets.layout().cloned();
        let new_snapshot: Snapshot = Arc::new(
            PolicySnapshot::from_policy_text_with_schema_and_stores(policy_text, schema, layout)?,
        );
        self.inner.store(new_snapshot);
        debug!(
            event = "PolicyReload",
            schema_enabled = had_schema,
            schema_reloaded = false
        );
        // Track reloads for metrics (no-op if feature disabled or no sink configured)
        #[cfg(feature = "observability")]
        record_reload();
        Ok(())
    }

    /// Reload policies and replace the engine schema at the same time.
    pub fn reload_from_str_with_schema(
        &self,
        policy_text: &str,
        schema: Schema,
    ) -> Result<(), PolicyError> {
        let current_snapshot = self.current_snapshot();
        let had_schema = current_snapshot.schema.is_some();
        let layout = current_snapshot.sets.layout().cloned();
        let new_snapshot: Snapshot =
            Arc::new(PolicySnapshot::from_policy_text_with_schema_and_stores(
                policy_text,
                Some(Arc::new(schema)),
                layout,
            )?);
        self.inner.store(new_snapshot);
        debug!(
            event = "PolicyReload",
            schema_enabled = true,
            schema_reloaded = true,
            schema_previously_enabled = had_schema
        );
        // Track reloads for metrics (no-op if feature disabled or no sink configured)
        #[cfg(feature = "observability")]
        record_reload();
        Ok(())
    }

    /// Reload policies and replace the engine schema from Cedar schema text.
    pub fn reload_from_str_with_cedarschema(
        &self,
        policy_text: &str,
        schema_text: &str,
    ) -> Result<(), PolicyError> {
        let schema: Schema = schema_text
            .parse()
            .map_err(|e| PolicyError::ParseError(format!("failed to parse Cedar schema: {e}")))?;
        self.reload_from_str_with_schema(policy_text, schema)
    }

    /// Get the current immutable snapshot.
    fn current_snapshot(&self) -> Snapshot {
        self.inner.load_full()
    }

    /// Get the current policy version.
    ///
    /// The `hash` is computed from the policy text, and `loaded_at` reflects
    /// when this snapshot was installed.
    pub fn current_version(&self) -> PolicyVersion {
        self.current_snapshot().version()
    }

    /// Return configured policy-store IDs, or `None` for a monolithic engine.
    pub fn policy_store_ids(&self) -> Option<Vec<PolicyStoreId>> {
        self.current_snapshot().sets.store_ids()
    }

    /// Prepare a request for authorization: accumulate labels, build Cedar entities, resolve groups.
    ///
    /// This separates request preparation from the authorization decision, making both
    /// more testable and the main hot path more readable.
    fn prepare(
        &self,
        request: &Request,
        request_context: Option<&RequestContext>,
    ) -> Result<PreparedRequest, PolicyError> {
        let snapshot = self.current_snapshot();
        let selected_store = snapshot.sets.resolve_store(request)?;
        let schema = snapshot.schema();
        #[cfg(feature = "observability")]
        let sink = get_sink();
        #[cfg(feature = "observability")]
        let metrics_enabled = metrics_enabled(&sink);
        #[cfg(not(feature = "observability"))]
        let metrics_enabled = false;
        let debug_enabled = tracing::enabled!(tracing::Level::DEBUG);
        let mut timers = EvalTimers::start(debug_enabled || metrics_enabled, debug_enabled);

        let groups = request_groups(request);

        if timers.debug_enabled {
            debug!(
                event = "Request",
                phase = "Evaluation",
                group_count = groups.map_or(0, Groups::len)
            );
        }

        // Convert each UID once after trusted label derivation is complete.
        let principal_uid = request.principal.cedar_entity_uid()?;
        let action_uid = request.action.cedar_entity_uid()?;

        let labelled_resource = if let Some(registry) = &self.label_registry {
            let labelled_resource = apply_labels(registry, &request.resource, &mut timers);
            if timers.debug_enabled {
                let resource_for_metrics = labelled_resource.as_ref().unwrap_or(&request.resource);
                debug!(
                    event = "Request",
                    phase = "LabelsApplied",
                    time = timers.labels.as_micros(),
                    attribute_count = resource_for_metrics.attributes().len()
                );
            }
            labelled_resource
        } else {
            if timers.debug_enabled {
                debug!(
                    event = "Request",
                    phase = "LabelsApplied",
                    time = timers.labels.as_micros()
                );
            }
            None
        };
        let resource_for_entities = labelled_resource.as_ref().unwrap_or(&request.resource);
        let resource_uid = resource_for_entities.cedar_entity_uid()?;
        let context = build_effective_context(request_context)?;

        if timers.debug_enabled {
            debug!(
                event = "Request",
                phase = "Parsed",
                group_count = groups.map_or(0, Groups::len),
                attribute_count = resource_for_entities.attributes().len(),
                request_context_attribute_count = request_context.map_or(0, RequestContext::len)
            );
        }

        // The request and entity graph both own the same principal and resource
        // IDs. Clone each UID once, then move both copies into Cedar instead of
        // cloning again inside both builders.
        let principal_uid_for_entities = principal_uid.clone();
        let resource_uid_for_entities = resource_uid.clone();

        // Build Cedar request with pre-converted UIDs
        let cedar_req = build_cedar_req(
            principal_uid,
            action_uid,
            resource_uid,
            context,
            schema,
            &mut timers,
        )?;

        // Build entities with pre-converted UIDs and potentially-modified resource
        let entities = build_entities(
            principal_uid_for_entities,
            resource_uid_for_entities,
            resource_for_entities,
            groups,
            schema,
            &mut timers,
        )?;

        if timers.debug_enabled {
            debug!(
                event = "Request",
                phase = "GroupsResolved",
                time = timers.groups.as_micros(),
            );
        }

        Ok(PreparedRequest {
            cedar_req,
            entities,
            snapshot,
            selected_store,
            timers,
            #[cfg(feature = "observability")]
            sink,
            #[cfg(feature = "observability")]
            metrics_enabled,
        })
    }

    /// Evaluate a policy request against the currently loaded policy set.
    ///
    /// This method performs a complete Cedar policy evaluation:
    /// 1. Applies any registered labelers to augment resource attributes
    /// 2. Constructs Cedar entities for the principal (including groups), action, and resource
    /// 3. Executes the Cedar authorization decision
    /// 4. Returns either `Allow` (with the matching policy) or `Deny`, both including version metadata
    ///
    /// # Arguments
    ///
    /// * `request` - The authorization request containing the principal, action, and resource
    ///
    /// # Returns
    ///
    /// * `Ok(Decision::Allow)` - If at least one permit policy matches and no forbid policies match
    /// * `Ok(Decision::Deny)` - If no permit policies match or if a forbid policy matches
    /// * `Err(PolicyError)` - If there's an error constructing entities, parsing the request, or during evaluation
    ///
    /// # Examples
    ///
    /// ```rust
    /// use treetop_core::{PolicyEngine, Request, Principal, User, Action, Resource, Decision};
    ///
    /// let policies = r#"
    ///     permit (
    ///         principal == User::"alice",
    ///         action == Action::"read",
    ///         resource == Document::"doc1"
    ///     );
    /// "#;
    ///
    /// let engine = PolicyEngine::new_from_str(policies).unwrap();
    ///
    /// let request = Request {
    ///     principal: Principal::User(User::new("alice", None, None)),
    ///     action: Action::new("read", None),
    ///     resource: Resource::new("Document", "doc1"),
    /// };
    ///
    /// let decision = engine.evaluate(&request).unwrap();
    /// assert!(matches!(decision, Decision::Allow { .. }));
    ///
    /// // Access version information
    /// if let Decision::Allow { version, .. } = decision {
    ///     println!("Allowed by policy version: {}", version.hash);
    /// }
    /// ```
    ///
    /// # Thread Safety
    ///
    /// This method is thread-safe and lock-free. Multiple threads can evaluate requests
    /// concurrently without blocking each other.
    #[cfg_attr(
        feature = "observability",
        tracing::instrument(name = "policy_evaluation", skip_all)
    )]
    pub fn evaluate(&self, request: &Request) -> Result<Decision, PolicyError> {
        Ok(self.evaluate_internal(request, None, false)?.decision)
    }

    /// Evaluate a request with explicit Cedar request context.
    pub fn evaluate_with_context(
        &self,
        request: &Request,
        request_context: &RequestContext,
    ) -> Result<Decision, PolicyError> {
        Ok(self
            .evaluate_internal(request, Some(request_context), false)?
            .decision)
    }

    /// Evaluate a request and include deny-side forbid diagnostics.
    pub fn evaluate_with_diagnostics(
        &self,
        request: &Request,
    ) -> Result<DecisionDiagnostics, PolicyError> {
        self.evaluate_internal(request, None, true)
    }

    /// Evaluate a request with explicit context and include deny diagnostics.
    pub fn evaluate_with_context_and_diagnostics(
        &self,
        request: &Request,
        request_context: &RequestContext,
    ) -> Result<DecisionDiagnostics, PolicyError> {
        self.evaluate_internal(request, Some(request_context), true)
    }

    fn evaluate_internal(
        &self,
        request: &Request,
        request_context: Option<&RequestContext>,
        include_forbid_diagnostics: bool,
    ) -> Result<DecisionDiagnostics, PolicyError> {
        // Prepare the request: apply labels, build entities, resolve groups
        let mut prepared = self.prepare(request, request_context)?;

        // Perform authorization with RAII timing (using cached Authorizer)
        let result = {
            let measure_enabled = prepared.timers.measure_enabled;
            let _timer = PhaseTimer::new_if(&mut prepared.timers.authz, measure_enabled);
            #[cfg(feature = "observability")]
            let _authz_span = info_span!("authorize").entered();
            let policy_set = prepared.snapshot.sets.selected(prepared.selected_store)?;
            get_authorizer().is_authorized(&prepared.cedar_req, policy_set, &prepared.entities)
        };

        if prepared.timers.debug_enabled {
            debug!(
                event = "Request",
                phase = "Authorized",
                time = prepared.timers.authz.as_micros(),
                decision = ?result.decision(),
            );
        }

        let version = prepared.snapshot.version();
        if prepared.timers.debug_enabled {
            debug!(
                event = "Request",
                phase = "Result",
                time = prepared.timers.total_elapsed().as_micros(),
                result = ?result.decision(),
                policy_hash = %version.hash,
                policy_loaded_at = %version.loaded_at,
            );
        }

        // Permit metadata is part of Allow decisions. Forbid IDs are only
        // materialized when the caller explicitly requests diagnostics. Metrics
        // borrow matching IDs from the Cedar response and compiled snapshot.
        let permit_policies = extract_permit_policies(&prepared.snapshot, &result);
        let collect_forbid_ids = include_forbid_diagnostics;
        let forbid_policy_ids = if collect_forbid_ids {
            extract_forbid_policy_ids(&prepared.snapshot, &result)
        } else {
            Vec::new()
        };
        let decision =
            Decision::from_decision_with_policy(result.decision(), permit_policies, version)?;

        // Record metrics (no-op when no sink is configured or feature disabled)
        #[cfg(feature = "observability")]
        {
            if prepared.metrics_enabled {
                let dur = prepared.timers.total_elapsed();
                let allowed = result.decision() == cedar_policy::Decision::Allow;
                let phases = EvaluationPhases {
                    apply_labels_ms: prepared.timers.labels.as_secs_f64() * 1000.0,
                    construct_entities_ms: prepared.timers.entities.as_secs_f64() * 1000.0,
                    resolve_groups_ms: prepared.timers.groups.as_secs_f64() * 1000.0,
                    authorize_ms: prepared.timers.authz.as_secs_f64() * 1000.0,
                    total_ms: dur.as_secs_f64() * 1000.0,
                };
                let matched_policies = match &decision {
                    Decision::Allow { policies, .. } => MatchedPolicySource::Allow(policies),
                    Decision::Deny { .. } => MatchedPolicySource::Deny {
                        diagnostics: result.diagnostics(),
                        policy_ids: &prepared.snapshot.forbid_policy_ids,
                    },
                };
                let observation = EvaluationObservation::new(
                    dur,
                    allowed,
                    &request.action,
                    phases,
                    matched_policies,
                );

                record_evaluation_observation(&prepared.sink, &observation);
            }
        }

        Ok(DecisionDiagnostics {
            decision,
            matched_forbid_policy_ids: forbid_policy_ids,
        })
    }

    /// List permit-policy candidates whose scope matches a user.
    ///
    /// This mirrors [`PolicyEngine::evaluate`] input shape for principal identity:
    /// user id + groups + shared namespace.
    ///
    /// Matching includes all Cedar principal-constraint forms:
    /// - `principal == User::"..."`
    /// - `principal in Group::"..."`
    /// - `principal`
    /// - `principal is User`
    /// - `principal is User in Group::"..."`
    ///
    /// Cedar `when` and `unless` clauses are not evaluated. The result is not
    /// an authorization decision; use [`PolicyEngine::evaluate`] to authorize.
    /// Resource constraints are not applied in this method. To additionally
    /// filter by policy resource constraints, use
    /// [`PolicyEngine::list_policies_for_user_with_resource`].
    ///
    /// Output is deterministic: policies are sorted by Cedar policy ID.
    /// Each returned policy includes match reasons via `UserPolicies::matches()`.
    ///
    /// # Arguments
    ///
    /// * `user` - User ID
    /// * `groups` - Group IDs the user belongs to
    /// * `namespace` - Optional shared namespace path for both user and groups
    ///
    /// # Returns
    ///
    /// * `Ok(UserPolicies)` - Matching policies and match metadata
    /// * `Err(PolicyError)` - If entity UID construction fails
    ///
    /// # Examples
    ///
    /// ```rust
    /// use treetop_core::PolicyEngine;
    ///
    /// let policies = r#"
    ///     permit (principal == User::"alice", action, resource);
    ///     permit (principal in Group::"admins", action, resource);
    /// "#;
    ///
    /// let engine = PolicyEngine::new_from_str(policies).unwrap();
    /// let user_policies = engine.list_policies_for_user("alice", &["admins"], &[]).unwrap();
    ///
    /// assert_eq!(user_policies.policies().len(), 2);
    /// assert!(!user_policies.matches().is_empty());
    /// ```
    pub fn list_policies_for_user(
        &self,
        user: &str,
        groups: &[&str],
        namespace: &[&str],
    ) -> Result<UserPolicies, PolicyError> {
        self.list_policies_for_user_with_resource_and_effect(
            user,
            groups,
            namespace,
            None,
            PolicyEffectFilter::Permit,
        )
    }

    /// List permit-policy candidates whose scope matches a concrete request.
    ///
    /// This mirrors [`PolicyEngine::evaluate`] by accepting `&Request` and uses:
    /// - the request principal (including user group membership, if any)
    /// - the request action
    /// - the request resource
    ///
    /// Cedar `when` and `unless` clauses are not evaluated. The result is not
    /// an authorization decision. This method defaults to permit policies; use
    /// [`PolicyEngine::list_policies_with_effect`] for an explicit effect.
    pub fn list_policies(&self, request: &Request) -> Result<UserPolicies, PolicyError> {
        self.list_policies_with_effect(request, PolicyEffectFilter::Permit)
    }

    /// List policy candidates for a request, with explicit effect filtering.
    ///
    /// Cedar `when` and `unless` clauses are not evaluated.
    pub fn list_policies_with_effect(
        &self,
        request: &Request,
        effect_filter: PolicyEffectFilter,
    ) -> Result<UserPolicies, PolicyError> {
        let principal = PrincipalQuery::from_principal(&request.principal)?;
        let action = ActionQuery::from_action(&request.action)?;
        self.list_policies_dispatch(
            &request.principal.to_string(),
            &principal,
            Some(&action),
            Some(&request.resource),
            effect_filter,
        )
    }

    /// List all policies applicable to a user, optionally filtering by resource constraints.
    ///
    /// This variant applies both principal and resource constraints:
    /// - principal constraints as described in [`PolicyEngine::list_policies_for_user`]
    /// - resource constraints (`==`, `in`, `is`, `is in`, `any`) when `resource` is provided
    ///
    /// When `resource` is `None`, behavior is equivalent to
    /// [`PolicyEngine::list_policies_for_user`].
    ///
    /// Returned `UserPolicies` includes match reasons for principal and, when
    /// applicable, resource matches.
    pub fn list_policies_for_user_with_resource(
        &self,
        user: &str,
        groups: &[&str],
        namespace: &[&str],
        resource: Option<&Resource>,
    ) -> Result<UserPolicies, PolicyError> {
        self.list_policies_for_user_with_resource_and_effect(
            user,
            groups,
            namespace,
            resource,
            PolicyEffectFilter::Permit,
        )
    }

    /// List all policies applicable to a user with optional resource and effect filtering.
    pub fn list_policies_for_user_with_resource_and_effect(
        &self,
        user: &str,
        groups: &[&str],
        namespace: &[&str],
        resource: Option<&Resource>,
        effect_filter: PolicyEffectFilter,
    ) -> Result<UserPolicies, PolicyError> {
        let principal = PrincipalQuery::for_user(user, groups, namespace)?;
        self.list_policies_dispatch(user, &principal, None, resource, effect_filter)
    }

    /// List all policies applicable to a group principal.
    ///
    /// Useful when callers model group identities directly as principals
    /// (mirroring `Principal::Group` in [`PolicyEngine::evaluate`]).
    ///
    /// Resource constraints are not applied in this method. To also filter by
    /// resource constraints, use
    /// [`PolicyEngine::list_policies_for_group_with_resource`].
    pub fn list_policies_for_group(
        &self,
        group: &str,
        namespace: &[&str],
    ) -> Result<UserPolicies, PolicyError> {
        self.list_policies_for_group_with_resource_and_effect(
            group,
            namespace,
            None,
            PolicyEffectFilter::Permit,
        )
    }

    /// List all policies applicable to a group principal, optionally filtering by resource constraints.
    ///
    /// This applies principal constraints for a group principal and, when
    /// `resource` is provided, resource constraints as well.
    pub fn list_policies_for_group_with_resource(
        &self,
        group: &str,
        namespace: &[&str],
        resource: Option<&Resource>,
    ) -> Result<UserPolicies, PolicyError> {
        self.list_policies_for_group_with_resource_and_effect(
            group,
            namespace,
            resource,
            PolicyEffectFilter::Permit,
        )
    }

    /// List all policies applicable to a group principal with optional resource and effect filtering.
    pub fn list_policies_for_group_with_resource_and_effect(
        &self,
        group: &str,
        namespace: &[&str],
        resource: Option<&Resource>,
        effect_filter: PolicyEffectFilter,
    ) -> Result<UserPolicies, PolicyError> {
        let principal = PrincipalQuery::for_group(group, namespace)?;
        self.list_policies_dispatch(group, &principal, None, resource, effect_filter)
    }

    fn list_policies_dispatch(
        &self,
        principal_id: &str,
        principal: &PrincipalQuery,
        action: Option<&ActionQuery>,
        resource: Option<&Resource>,
        effect_filter: PolicyEffectFilter,
    ) -> Result<UserPolicies, PolicyError> {
        let snapshot = self.current_snapshot();
        let resource_query = match resource {
            Some(resource) => Some(ResourceQuery::from_resource(resource)?),
            None => None,
        };
        let mut matching_policies: Vec<(Policy, Vec<PolicyMatchReason>)> = Vec::new();
        let mut seen_policy_ids = HashSet::new();

        for set in snapshot.sets.iter() {
            for policy in set.policies() {
                if !seen_policy_ids.insert(policy.id().clone()) {
                    continue;
                }
                if !matches_effect(policy.effect(), effect_filter) {
                    continue;
                }

                let Some(principal_reason) =
                    principal_match_reason(policy.principal_constraint(), principal)
                else {
                    continue;
                };

                let Some(action_reason) = action_match_reason(policy.action_constraint(), action)
                else {
                    continue;
                };

                let Some(resource_reason) =
                    resource_match_reason(policy.resource_constraint(), resource_query.as_ref())
                else {
                    continue;
                };

                let mut reasons = vec![principal_reason];
                if let Some(action_reason) = action_reason {
                    reasons.push(action_reason);
                }
                if let Some(resource_reason) = resource_reason {
                    reasons.push(resource_reason);
                }

                matching_policies.push((policy.clone(), reasons));
            }
        }

        Ok(UserPolicies::new_with_matches(
            principal_id,
            matching_policies,
        ))
    }

    pub fn policies(&self) -> Result<Vec<Policy>, PolicyError> {
        let snapshot = self.current_snapshot();
        match &snapshot.sets {
            PolicySets::Monolithic(set) => Ok(set.policies().cloned().collect()),
            PolicySets::Scoped { .. } => {
                let mut seen_policy_ids = HashSet::new();
                let mut policies = snapshot
                    .sets
                    .iter()
                    .flat_map(PolicySet::policies)
                    .filter(|policy| seen_policy_ids.insert(policy.id().clone()))
                    .cloned()
                    .collect::<Vec<_>>();
                policies.sort_by(|left, right| left.id().cmp(right.id()));
                Ok(policies)
            }
        }
    }
}

#[cfg(test)]
mod tests;