cedarling 2.3.0

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
// 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.

#[cfg(test)]
mod archive_security_tests;
pub(crate) mod log_entry;
#[cfg(test)]
pub(crate) mod test_utils;
pub(crate) mod token_entity_metadata;

use crate::common::{
    default_entities::DefaultEntitiesWithWarns,
    issuer_utils::IssClaim,
};

pub(crate) mod archive_handler;
pub(crate) mod entity_parser;
pub(crate) mod errors;
pub(crate) mod issuer_parser;
pub(crate) mod legacy_store;
pub(crate) mod loader;
pub(crate) mod manager;
pub(crate) mod metadata;
pub(crate) mod policy_parser;
pub(crate) mod schema_parser;
pub(crate) mod validator;
pub(crate) mod vfs_adapter;

use super::cedar_schema::CedarSchema;
use cedar_policy::{ActionConstraint, Effect, EntityTypeName, EntityUid, Policy, PolicyId};
use serde::Serialize;
use std::collections::{HashMap, HashSet};
use url::Url;

pub(crate) use token_entity_metadata::TokenEntityMetadata;

// Re-export types used by init/policy_store.rs and external consumers
pub(crate) use manager::ConversionError;
pub(crate) use metadata::PolicyStoreMetadata;

/// Represents the store of policies used for JWT validation and policy evaluation in Cedarling.
///
/// The `PolicyStore` contains the schema and a set of policies encoded in base64,
/// which are parsed during deserialization.
#[derive(Debug, Clone)]
#[cfg_attr(test, derive(PartialEq))]
pub(crate) struct PolicyStore {
    /// version of policy store
    //
    // alias to support Agama lab format
    pub(crate) version: Option<String>,

    /// Cedar schema (optional — `None` when strict schema validation is disabled)
    pub(crate) schema: Option<CedarSchema>,

    /// Whether a schema source was present in the policy store source,
    /// regardless of whether it was loaded (used for log messages).
    pub(crate) schema_source_exists: bool,

    /// Cedar policy set
    pub(crate) policies: PoliciesContainer,

    /// An optional `HashMap` of trusted issuers.
    ///
    /// This field may contain issuers that are trusted to provide tokens, allowing for additional
    /// verification and security when handling JWTs.
    pub(crate) trusted_issuers: Option<HashMap<String, TrustedIssuer>>,

    /// Default entities for the policy store.
    pub(crate) default_entities: DefaultEntitiesWithWarns,
}

impl PolicyStore {
    pub(crate) fn get_store_version(&self) -> &str {
        self.version.as_deref().unwrap_or("undefined")
    }

    pub(crate) fn validate_trusted_issuers(&self) -> Result<(), TrustedIssuersValidationError> {
        // check if iss already present in other policy store
        let mut oidc_to_trusted_issuer: HashMap<String, String> = HashMap::new();

        for (issuer_name, trusted_issuer) in self.trusted_issuers.iter().flatten() {
            let oidc_url = trusted_issuer.oidc_endpoint.to_string();
            if let Some(_previous_issuer_name) = oidc_to_trusted_issuer.get(&oidc_url) {
                return Err(TrustedIssuersValidationError {
                    oidc_url: format!(
                        "openid_configuration_endpoint: '{oidc_url}' is used for more than one issuer"
                    ),
                });
            }
            oidc_to_trusted_issuer.insert(oidc_url, issuer_name.to_owned());
        }

        Ok(())
    }
}

#[derive(Debug, derive_more::Display, derive_more::Error)]
#[display("openid_configuration_endpoint: '{oidc_url}' is used for more than one issuer")]
pub(crate) struct TrustedIssuersValidationError {
    oidc_url: String,
}

/// Wrapper around [`PolicyStore`] to have access to it and ID of policy store.
///
/// When loaded from the new directory/archive format, includes optional metadata
/// containing version, description, and other policy store information.
#[derive(Clone, derive_more::Deref)]
#[cfg_attr(test, derive(Debug))]
pub(crate) struct PolicyStoreWithID {
    /// ID of policy store
    pub(crate) id: String,
    /// Policy store value
    #[deref]
    pub(crate) store: PolicyStore,
    /// Optional metadata from new format policy stores.
    /// Contains `cedar_version`, `policy_store` info (name, version, description, etc.)
    pub(crate) metadata: Option<metadata::PolicyStoreMetadata>,
}

/// Represents a trusted issuer that can provide JWTs.
///
/// This struct includes the issuer's name, description, and the `OpenID` configuration endpoint
/// for discovering issuer-related information.
#[derive(Debug, Clone, PartialEq)]
pub(crate) struct TrustedIssuer {
    /// The name of the trusted issuer.
    /// Name also describe namespace in Cedar policy where entity `TrustedIssuer` is located.
    pub(crate) name: String,
    /// A brief description of the trusted issuer.
    pub(crate) description: String,
    /// The `OpenID` configuration endpoint for the issuer.
    ///
    /// This endpoint is used to obtain information about the issuer's capabilities.
    // Private to force usage of `iss_claim` method to get normalized iss claim
    oidc_endpoint: Url,
    /// Metadata for tokens issued by the trusted issuer.
    pub(crate) token_metadata: HashMap<String, TokenEntityMetadata>,
}

#[cfg(test)]
impl Default for TrustedIssuer {
    fn default() -> Self {
        Self {
            name: "Jans".to_string(),
            description: String::default(),
            // This will only really be called during testing so we just put this test value
            oidc_endpoint: Url::parse("https://test.jans.org/.well-known/openid-configuration")
                .unwrap(),
            token_metadata: HashMap::from([
                ("access_token".into(), TokenEntityMetadata::access_token()),
                ("id_token".into(), TokenEntityMetadata::id_token()),
                (
                    "userinfo_token".into(),
                    TokenEntityMetadata::userinfo_token(),
                ),
            ]),
        }
    }
}

#[cfg(test)]
impl Default for &TrustedIssuer {
    fn default() -> Self {
        static DEFAULT: std::sync::LazyLock<TrustedIssuer> =
            std::sync::LazyLock::new(TrustedIssuer::default);
        &DEFAULT
    }
}

impl TrustedIssuer {
    pub(crate) fn new(
        name: String,
        description: String,
        oidc_endpoint: Url,
        metadata: HashMap<String, TokenEntityMetadata>,
    ) -> Self {
        Self {
            name,
            description,
            oidc_endpoint,
            token_metadata: metadata,
        }
    }

    #[cfg(test)]
    pub(crate) fn set_oidc_endpoint(&mut self, url: Url) {
        self.oidc_endpoint = url;
    }

    /// Get the OIDC endpoint URL.
    /// Should be used when we need to make requests to the OIDC endpoint.
    ///
    /// If you need comparison with `iss` claim, use `iss_claim` method instead.
    pub(crate) fn get_oidc_endpoint(&self) -> &Url {
        &self.oidc_endpoint
    }

    pub(crate) fn iss_claim(&self) -> IssClaim {
        IssClaim::new(&self.oidc_endpoint.origin().ascii_serialization())
    }
}

/// Container for compiled Cedar policies and their descriptions.
#[derive(Debug, Clone)]
pub(crate) struct PoliciesContainer {
    /// Policy descriptions by ID
    descriptions: HashMap<String, String>,
    /// Compiled `cedar_policy` Policy set
    policy_set: cedar_policy::PolicySet,
}

#[cfg(test)]
impl PartialEq for PoliciesContainer {
    fn eq(&self, other: &Self) -> bool {
        use std::collections::BTreeMap;
        let self_policies: BTreeMap<_, _> = self
            .policy_set
            .policies()
            .map(|p| (p.id().clone(), p))
            .collect();
        let other_policies: BTreeMap<_, _> = other
            .policy_set
            .policies()
            .map(|p| (p.id().clone(), p))
            .collect();
        self_policies == other_policies
    }
}

impl PoliciesContainer {
    /// Create a new `PoliciesContainer` from a policy set and description map.
    pub(crate) fn new(policy_set: cedar_policy::PolicySet, descriptions: HashMap<String, String>) -> Self {
        Self {
            descriptions,
            policy_set,
        }
    }

    /// Create an empty `PoliciesContainer` with the given policy set.
    pub(crate) fn new_empty(policy_set: cedar_policy::PolicySet) -> Self {
        Self {
            policy_set,
            descriptions: HashMap::new(),
        }
    }

    /// Get [`cedar_policy::PolicySet`]
    pub(crate) fn get_set(&self) -> &cedar_policy::PolicySet {
        &self.policy_set
    }

    /// Get policy description based on id of policy
    pub(crate) fn get_policy_description(&self, id: &str) -> Option<&str> {
        self.descriptions.get(id).map(String::as_str)
    }

    /// Returns metadata for all policies whose scope constraints are compatible
    /// with the given principal types, action UIDs, and resource types.
    ///
    /// Filtering is scope-level only: policies with `when`/`unless` conditions
    /// may still not apply at evaluation time. The returned set is a superset
    /// of truly applicable policies.
    pub(crate) fn get_matching_policies(
        &self,
        principal_entity_type_names: &HashSet<EntityTypeName>,
        action_uids: &HashSet<EntityUid>,
        resource_entity_type_names: &HashSet<EntityTypeName>,
    ) -> Vec<PolicyMetadata> {
        self.policy_set
            .policies()
            .filter(|policy| {
                matches_principal(policy, principal_entity_type_names)
                    && matches_action(policy, action_uids)
                    && matches_resource(policy, resource_entity_type_names)
            })
            .map(PolicyMetadata::from_policy)
            .collect()
    }

    /// Merge the annotations of the given policies into a single map.
    ///
    /// Lossy: if the same annotation key appears on several policies, one value
    /// wins arbitrarily (iteration order is undefined). Use [`Self::annotation_values`]
    /// or [`Self::annotations_by_policy`] when duplicates matter.
    /// IDs not present in the policy set are silently skipped.
    pub(crate) fn annotations_map<'a>(
        &self,
        ids: impl IntoIterator<Item = &'a PolicyId>,
    ) -> HashMap<String, String> {
        ids.into_iter()
            .filter_map(|id| self.policy_set.policy(id))
            .flat_map(Policy::annotations)
            .map(|(k, v)| (k.to_string(), v.to_string()))
            .collect()
    }

    /// Collect every value of the annotation `key` across the given policies.
    ///
    /// Duplicates are preserved; IDs not present in the policy set are silently skipped.
    pub(crate) fn annotation_values<'a>(
        &self,
        ids: impl IntoIterator<Item = &'a PolicyId>,
        key: &str,
    ) -> Vec<String> {
        ids.into_iter()
            .filter_map(|id| self.policy_set.policy(id))
            .flat_map(Policy::annotations)
            .filter(|(k, _)| *k == key)
            .map(|(_, v)| v.to_string())
            .collect()
    }

    /// Return the annotations of each given policy, grouped by policy ID.
    ///
    /// Loss-free companion to [`Self::annotations_map`]. IDs not present in the
    /// policy set are silently skipped.
    pub(crate) fn annotations_by_policy<'a>(
        &self,
        ids: impl IntoIterator<Item = &'a PolicyId>,
    ) -> HashMap<String, HashMap<String, String>> {
        ids.into_iter()
            .filter_map(|id| self.policy_set.policy(id))
            .map(|policy| {
                (
                    policy.id().to_string(),
                    policy
                        .annotations()
                        .map(|(k, v)| (k.to_string(), v.to_string()))
                        .collect(),
                )
            })
            .collect()
    }
}

/// The effect of a Cedar policy: either `Permit` or `Forbid`.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
#[serde(rename_all = "lowercase")]
pub enum PolicyEffect {
    /// The policy permits the request.
    Permit,
    /// The policy forbids the request.
    Forbid,
}

impl From<Effect> for PolicyEffect {
    fn from(effect: Effect) -> Self {
        match effect {
            Effect::Permit => PolicyEffect::Permit,
            Effect::Forbid => PolicyEffect::Forbid,
        }
    }
}

/// Metadata about a single Cedar policy.
#[derive(Debug, Clone, PartialEq, Serialize)]
pub struct PolicyMetadata {
    /// The policy ID
    pub id: String,
    /// The effect of the policy (`Permit` or `Forbid`)
    pub effect: PolicyEffect,
    /// Key-value pairs from Cedar policy annotations (`@key("value")`)
    pub annotations: HashMap<String, String>,
    /// The Cedar policy source code (human-readable Cedar syntax)
    pub source: String,
}

impl PolicyMetadata {
    fn from_policy(policy: &Policy) -> Self {
        Self {
            id: policy.id().to_string(),
            effect: policy.effect().into(),
            annotations: policy
                .annotations()
                .map(|(k, v)| (k.to_string(), v.to_string()))
                .collect(),
            source: policy.to_string(),
        }
    }
}

/// Check if a policy's principal scope constraint matches any of the given principal entity types.
fn matches_principal(policy: &Policy, principal_types: &HashSet<EntityTypeName>) -> bool {
    use cedar_policy::PrincipalConstraint;
    match policy.principal_constraint() {
        PrincipalConstraint::Any => true,
        PrincipalConstraint::Eq(euid) | PrincipalConstraint::In(euid) => {
            principal_types.contains(euid.type_name())
        },
        PrincipalConstraint::Is(type_name) | PrincipalConstraint::IsIn(type_name, _) => {
            principal_types.contains(&type_name)
        },
    }
}

/// Check if a policy's action scope constraint matches any of the given action UIDs.
fn matches_action(policy: &Policy, action_uids: &HashSet<EntityUid>) -> bool {
    match policy.action_constraint() {
        ActionConstraint::Any => true,
        ActionConstraint::Eq(euid) => action_uids.contains(&euid),
        ActionConstraint::In(euids) => euids.iter().any(|euid| action_uids.contains(euid)),
    }
}

/// Check if a policy's resource scope constraint matches any of the given resource entity types.
fn matches_resource(policy: &Policy, resource_types: &HashSet<EntityTypeName>) -> bool {
    use cedar_policy::ResourceConstraint;
    match policy.resource_constraint() {
        ResourceConstraint::Any => true,
        ResourceConstraint::Eq(euid) | ResourceConstraint::In(euid) => {
            resource_types.contains(euid.type_name())
        },
        ResourceConstraint::Is(type_name) | ResourceConstraint::IsIn(type_name, _) => {
            resource_types.contains(&type_name)
        },
    }
}

#[cfg(test)]
mod policy_metadata_tests {
    use super::*;
    use cedar_policy::{EntityTypeName, EntityUid, PolicyId, PolicySet};
    use std::collections::HashSet;
    use std::str::FromStr;

    /// Helper: build a `PoliciesContainer` from individual policies with explicit IDs.
    fn make_container(policies: &[(&str, &str)]) -> PoliciesContainer {
        let mut policy_set = PolicySet::new();
        for (id, src) in policies {
            let policy = Policy::parse(Some(PolicyId::new(id)), *src).expect("bad policy");
            policy_set.add(policy).expect("duplicate policy id");
        }
        PoliciesContainer::new_empty(policy_set)
    }

    fn type_names(names: &[&str]) -> HashSet<EntityTypeName> {
        names
            .iter()
            .map(|n| EntityTypeName::from_str(n).unwrap())
            .collect()
    }

    fn action_uids(actions: &[&str]) -> HashSet<EntityUid> {
        actions
            .iter()
            .map(|a| EntityUid::from_str(a).unwrap())
            .collect()
    }

    #[test]
    fn matches_all_policies_with_any_constraints() {
        let container = make_container(&[("open", "permit(principal, action, resource);")]);

        let result = container.get_matching_policies(
            &type_names(&["Foo::Bar"]),
            &action_uids(&[r#"Foo::Action::"read""#]),
            &type_names(&["Foo::Resource"]),
        );

        assert_eq!(result.len(), 1);
        assert_eq!(result[0].id, "open");
    }

    #[test]
    fn filters_by_action() {
        let container = make_container(&[
            (
                "read_policy",
                r#"permit(principal, action == Jans::Action::"Read", resource);"#,
            ),
            (
                "write_policy",
                r#"permit(principal, action == Jans::Action::"Write", resource);"#,
            ),
        ]);

        let result = container.get_matching_policies(
            &type_names(&["Jans::User"]),
            &action_uids(&[r#"Jans::Action::"Read""#]),
            &type_names(&["Jans::Document"]),
        );

        assert_eq!(result.len(), 1);
        assert_eq!(result[0].id, "read_policy");
    }

    #[test]
    fn filters_by_principal_type() {
        let container = make_container(&[
            (
                "workload_policy",
                "permit(principal is Jans::Workload, action, resource);",
            ),
            (
                "user_policy",
                "permit(principal is Jans::User, action, resource);",
            ),
        ]);

        let result = container.get_matching_policies(
            &type_names(&["Jans::User"]),
            &action_uids(&[r#"Jans::Action::"Read""#]),
            &type_names(&["Jans::Doc"]),
        );

        assert_eq!(result.len(), 1);
        assert_eq!(result[0].id, "user_policy");
    }

    #[test]
    fn filters_by_resource_type() {
        let container = make_container(&[
            (
                "issue_policy",
                "permit(principal, action, resource is Jans::Issue);",
            ),
            (
                "doc_policy",
                "permit(principal, action, resource is Jans::Document);",
            ),
        ]);

        let result = container.get_matching_policies(
            &type_names(&["Jans::User"]),
            &action_uids(&[r#"Jans::Action::"Read""#]),
            &type_names(&["Jans::Issue"]),
        );

        assert_eq!(result.len(), 1);
        assert_eq!(result[0].id, "issue_policy");
    }

    #[test]
    fn combined_filtering() {
        let container = make_container(&[
            (
                "specific",
                r#"permit(
                    principal is Jans::User,
                    action == Jans::Action::"Read",
                    resource is Jans::Document
                );"#,
            ),
            (
                "other_action",
                r#"permit(
                    principal is Jans::User,
                    action == Jans::Action::"Delete",
                    resource is Jans::Document
                );"#,
            ),
            (
                "other_principal",
                r#"permit(
                    principal is Jans::Workload,
                    action == Jans::Action::"Read",
                    resource is Jans::Document
                );"#,
            ),
        ]);

        let result = container.get_matching_policies(
            &type_names(&["Jans::User"]),
            &action_uids(&[r#"Jans::Action::"Read""#]),
            &type_names(&["Jans::Document"]),
        );

        assert_eq!(result.len(), 1);
        assert_eq!(result[0].id, "specific");
    }

    #[test]
    fn action_in_constraint() {
        let container = make_container(&[(
            "multi_action",
            r#"permit(
                principal,
                action in [Jans::Action::"Read", Jans::Action::"List"],
                resource
            );"#,
        )]);

        let result = container.get_matching_policies(
            &type_names(&["Jans::User"]),
            &action_uids(&[r#"Jans::Action::"Read""#]),
            &type_names(&["Jans::Doc"]),
        );
        assert_eq!(result.len(), 1);

        let result = container.get_matching_policies(
            &type_names(&["Jans::User"]),
            &action_uids(&[r#"Jans::Action::"Delete""#]),
            &type_names(&["Jans::Doc"]),
        );
        assert_eq!(result.len(), 0);
    }

    #[test]
    fn annotations_are_extracted() {
        let mut policy_set = PolicySet::new();
        let policy = Policy::parse(
            Some(PolicyId::new("annotated")),
            r#"
            @description("Allow users to read docs")
            @category("access_control")
            permit(principal, action, resource);
            "#,
        )
        .unwrap();
        policy_set.add(policy).unwrap();
        let container = PoliciesContainer::new_empty(policy_set);

        let result = container.get_matching_policies(
            &type_names(&["Jans::User"]),
            &action_uids(&[r#"Jans::Action::"Read""#]),
            &type_names(&["Jans::Doc"]),
        );

        assert_eq!(result.len(), 1);
        let policy = &result[0];
        assert_eq!(
            policy.annotations.get("description").unwrap(),
            "Allow users to read docs"
        );
        assert_eq!(
            policy.annotations.get("category").unwrap(),
            "access_control"
        );
    }

    #[test]
    fn source_is_recoverable() {
        let container = make_container(&[("p", "permit(principal, action, resource);")]);

        let result = container.get_matching_policies(
            &type_names(&["Any::Type"]),
            &action_uids(&[r#"Any::Action::"do""#]),
            &type_names(&["Any::Res"]),
        );

        assert_eq!(result.len(), 1);
        assert!(result[0].source.contains("permit"));
    }

    #[test]
    fn empty_inputs_return_only_any_policies() {
        let container = make_container(&[
            ("any_policy", "permit(principal, action, resource);"),
            (
                "specific_policy",
                r#"permit(
                    principal is Jans::User,
                    action == Jans::Action::"Read",
                    resource is Jans::Doc
                );"#,
            ),
        ]);

        let result =
            container.get_matching_policies(&HashSet::new(), &HashSet::new(), &HashSet::new());

        // Only the "any" policy matches — specific constraints can't match empty sets
        assert_eq!(result.len(), 1);
        assert_eq!(result[0].id, "any_policy");
    }

    #[test]
    fn multiple_principals_match_union() {
        let container = make_container(&[
            (
                "workload_policy",
                "permit(principal is Jans::Workload, action, resource);",
            ),
            (
                "user_policy",
                "permit(principal is Jans::User, action, resource);",
            ),
        ]);

        let result = container.get_matching_policies(
            &type_names(&["Jans::User", "Jans::Workload"]),
            &action_uids(&[r#"Jans::Action::"Read""#]),
            &type_names(&["Jans::Doc"]),
        );

        assert_eq!(result.len(), 2);
    }

    fn annotated_container() -> PoliciesContainer {
        make_container(&[
            (
                "upgrade",
                r#"
                @redirect("/upgrade")
                @tier("premium")
                permit(principal, action, resource);
                "#,
            ),
            (
                "trial",
                r#"
                @redirect("/trial")
                @audit("true")
                permit(principal, action, resource);
                "#,
            ),
        ])
    }

    #[test]
    fn annotations_map_merges_policies() {
        let container = annotated_container();
        let ids = [PolicyId::new("upgrade"), PolicyId::new("trial")];

        let result = container.annotations_map(ids.iter());

        // "redirect" collides across policies: one value survives, order undefined
        assert_eq!(result.len(), 3);
        assert!(["/upgrade", "/trial"].contains(&result["redirect"].as_str()));
        assert_eq!(result["tier"], "premium");
        assert_eq!(result["audit"], "true");
    }

    #[test]
    fn annotations_map_skips_missing_ids() {
        let container = annotated_container();
        let ids = [PolicyId::new("upgrade"), PolicyId::new("no_such_policy")];

        let result = container.annotations_map(ids.iter());

        assert_eq!(result.len(), 2);
        assert_eq!(result["redirect"], "/upgrade");
        assert_eq!(result["tier"], "premium");
    }

    #[test]
    fn annotation_values_preserves_duplicates() {
        let container = annotated_container();
        let ids = [PolicyId::new("upgrade"), PolicyId::new("trial")];

        let mut result = container.annotation_values(ids.iter(), "redirect");
        result.sort();
        assert_eq!(result, ["/trial", "/upgrade"]);

        assert_eq!(container.annotation_values(ids.iter(), "audit"), ["true"]);
        assert!(container.annotation_values(ids.iter(), "absent").is_empty());
    }

    #[test]
    fn annotations_by_policy_groups_per_policy() {
        let container = annotated_container();
        let ids = [
            PolicyId::new("upgrade"),
            PolicyId::new("trial"),
            PolicyId::new("no_such_policy"),
        ];

        let result = container.annotations_by_policy(ids.iter());

        assert_eq!(result.len(), 2);
        assert_eq!(result["upgrade"]["redirect"], "/upgrade");
        assert_eq!(result["upgrade"]["tier"], "premium");
        assert_eq!(result["trial"]["redirect"], "/trial");
        assert_eq!(result["trial"]["audit"], "true");
    }

    #[test]
    fn annotations_of_unannotated_policy_are_empty() {
        let container = make_container(&[("plain", "permit(principal, action, resource);")]);
        let ids = [PolicyId::new("plain")];

        assert!(container.annotations_map(ids.iter()).is_empty());
        assert!(container.annotation_values(ids.iter(), "any").is_empty());

        let by_policy = container.annotations_by_policy(ids.iter());
        assert_eq!(by_policy.len(), 1);
        assert!(by_policy["plain"].is_empty());
    }
}