cedar_policy_core/authorizer/
partial_response.rs

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

use std::collections::HashMap;

use either::Either;
use smol_str::SmolStr;
use std::sync::Arc;

use super::{
    err::{ConcretizationError, ReauthorizationError},
    Annotations, AuthorizationError, Authorizer, Context, Decision, Effect, EntityUIDEntry, Expr,
    Policy, PolicySet, PolicySetError, Request, Response, Value,
};
use crate::{ast::PolicyID, entities::Entities, evaluator::EvaluationError};

type PolicyComponents<'a> = (Effect, &'a PolicyID, &'a Arc<Expr>, &'a Arc<Annotations>);

/// Enum representing whether a policy is not satisfied due to
/// evaluating to `false`, or because it errored.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum ErrorState {
    /// The policy did not error
    NoError,
    /// The policy did error
    Error,
}

/// A partially evaluated authorization response.
/// Splits the results into several categories: satisfied, false, and residual for each policy effect.
/// Also tracks all the errors that were encountered during evaluation.
/// This structure currently has to own all of the `PolicyID` objects due to the [`Self::reauthorize`]
/// method. If [`PolicySet`] could borrow its PolicyID/contents then this whole structured could be borrowed.
#[derive(Debug, Clone)]
pub struct PartialResponse {
    /// All of the [`Effect::Permit`] policies that were satisfied
    pub satisfied_permits: HashMap<PolicyID, Arc<Annotations>>,
    /// All of the [`Effect::Permit`] policies that were not satisfied
    pub false_permits: HashMap<PolicyID, (ErrorState, Arc<Annotations>)>,
    /// All of the [`Effect::Permit`] policies that evaluated to a residual
    pub residual_permits: HashMap<PolicyID, (Arc<Expr>, Arc<Annotations>)>,
    /// All of the [`Effect::Forbid`] policies that were satisfied
    pub satisfied_forbids: HashMap<PolicyID, Arc<Annotations>>,
    /// All of the [`Effect::Forbid`] policies that were not satisfied
    pub false_forbids: HashMap<PolicyID, (ErrorState, Arc<Annotations>)>,
    /// All of the [`Effect::Forbid`] policies that evaluated to a residual
    pub residual_forbids: HashMap<PolicyID, (Arc<Expr>, Arc<Annotations>)>,
    /// All of the policy errors encountered during evaluation
    pub errors: Vec<AuthorizationError>,
    /// The trivial `true` expression, used for materializing a residual for satisfied policies
    true_expr: Arc<Expr>,
    /// The trivial `false` expression, used for materializing a residual for non-satisfied policies
    false_expr: Arc<Expr>,
    /// The request associated with the partial response
    request: Arc<Request>,
}

impl PartialResponse {
    /// Create a partial response from each of the policy result categories
    #[allow(clippy::too_many_arguments)]
    pub fn new(
        true_permits: impl IntoIterator<Item = (PolicyID, Arc<Annotations>)>,
        false_permits: impl IntoIterator<Item = (PolicyID, (ErrorState, Arc<Annotations>))>,
        residual_permits: impl IntoIterator<Item = (PolicyID, (Arc<Expr>, Arc<Annotations>))>,
        true_forbids: impl IntoIterator<Item = (PolicyID, Arc<Annotations>)>,
        false_forbids: impl IntoIterator<Item = (PolicyID, (ErrorState, Arc<Annotations>))>,
        residual_forbids: impl IntoIterator<Item = (PolicyID, (Arc<Expr>, Arc<Annotations>))>,
        errors: impl IntoIterator<Item = AuthorizationError>,
        request: Arc<Request>,
    ) -> Self {
        Self {
            satisfied_permits: true_permits.into_iter().collect(),
            false_permits: false_permits.into_iter().collect(),
            residual_permits: residual_permits.into_iter().collect(),
            satisfied_forbids: true_forbids.into_iter().collect(),
            false_forbids: false_forbids.into_iter().collect(),
            residual_forbids: residual_forbids.into_iter().collect(),
            errors: errors.into_iter().collect(),
            true_expr: Arc::new(Expr::val(true)),
            false_expr: Arc::new(Expr::val(false)),
            request,
        }
    }

    /// Convert this response into a concrete evaluation response.
    /// All residuals are treated as errors
    pub fn concretize(self) -> Response {
        self.into()
    }

    /// Attempt to reach a partial decision; the presence of residuals may result in returning [`None`],
    /// indicating that a decision could not be reached given the unknowns
    pub fn decision(&self) -> Option<Decision> {
        match (
            !self.satisfied_forbids.is_empty(),
            !self.satisfied_permits.is_empty(),
            !self.residual_permits.is_empty(),
            !self.residual_forbids.is_empty(),
        ) {
            // Any true forbids means we will deny
            (true, _, _, _) => Some(Decision::Deny),
            // No potentially or trivially true permits, means we default deny
            (_, false, false, _) => Some(Decision::Deny),
            // Potentially true forbids, means we can't know (as that forbid may evaluate to true, overriding any permits)
            (false, _, _, true) => None,
            // No true permits, but some potentially true permits + no true/potentially true forbids means we don't know
            (false, false, true, false) => None,
            // At least one trivially true permit, and no trivially or possible true forbids, means we allow
            (false, true, _, false) => Some(Decision::Allow),
        }
    }

    /// All of the [`Effect::Permit`] policies that were known to be satisfied
    fn definitely_satisfied_permits(&self) -> impl Iterator<Item = Policy> + '_ {
        self.satisfied_permits.iter().map(|(id, annotations)| {
            construct_policy((Effect::Permit, id, &self.true_expr, annotations))
        })
    }

    /// All of the [`Effect::Forbid`] policies that were known to be satisfied
    fn definitely_satisfied_forbids(&self) -> impl Iterator<Item = Policy> + '_ {
        self.satisfied_forbids.iter().map(|(id, annotations)| {
            construct_policy((Effect::Forbid, id, &self.true_expr, annotations))
        })
    }

    /// Returns the set of [`PolicyID`]s that were definitely satisfied -- both permits and forbids
    pub fn definitely_satisfied(&self) -> impl Iterator<Item = Policy> + '_ {
        self.definitely_satisfied_permits()
            .chain(self.definitely_satisfied_forbids())
    }

    /// Returns the set of [`PolicyID`]s that encountered errors
    pub fn definitely_errored(&self) -> impl Iterator<Item = &PolicyID> {
        self.false_permits
            .iter()
            .chain(self.false_forbids.iter())
            .filter_map(did_error)
    }

    /// Returns an over-approximation of the set of determining policies.
    ///
    /// This is all policies that may be determining for any substitution of the unknowns.
    pub fn may_be_determining(&self) -> impl Iterator<Item = Policy> + '_ {
        if self.satisfied_forbids.is_empty() {
            // We have no definitely true forbids, so the over approx is everything that is true or potentially true
            Either::Left(
                self.definitely_satisfied_permits()
                    .chain(self.residual_permits())
                    .chain(self.residual_forbids()),
            )
        } else {
            // We have definitely true forbids, so we know only things that can determine is
            // true forbids and potentially true forbids
            Either::Right(
                self.definitely_satisfied_forbids()
                    .chain(self.residual_forbids()),
            )
        }
    }

    fn residual_permits(&self) -> impl Iterator<Item = Policy> + '_ {
        self.residual_permits
            .iter()
            .map(|(id, (expr, annotations))| {
                construct_policy((Effect::Permit, id, expr, annotations))
            })
    }

    fn residual_forbids(&self) -> impl Iterator<Item = Policy> + '_ {
        self.residual_forbids
            .iter()
            .map(|(id, (expr, annotations))| {
                construct_policy((Effect::Forbid, id, expr, annotations))
            })
    }

    /// Returns an under-approximation of the set of determining policies.
    ///
    /// This is all policies that must be determining for all possible substitutions of the unknowns.
    pub fn must_be_determining(&self) -> impl Iterator<Item = Policy> + '_ {
        // If there are no true forbids or potentially true forbids,
        // then the under approximation is the true permits
        if self.satisfied_forbids.is_empty() && self.residual_forbids.is_empty() {
            Either::Left(self.definitely_satisfied_permits())
        } else {
            // Otherwise it's the true forbids
            Either::Right(self.definitely_satisfied_forbids())
        }
    }

    /// Returns the set of non-trivial (meaning more than just `true` or `false`) residuals expressions
    pub fn nontrivial_residuals(&'_ self) -> impl Iterator<Item = Policy> + '_ {
        self.nontrival_permits().chain(self.nontrival_forbids())
    }

    /// Returns the set of ids of non-trivial (meaning more than just `true` or `false`) residuals expressions
    pub fn nontrivial_residual_ids(&self) -> impl Iterator<Item = &PolicyID> {
        self.residual_permits
            .keys()
            .chain(self.residual_forbids.keys())
    }

    /// Returns the set of non-trivial (meaning more than just `true` or `false`) residuals expressions from [`Effect::Permit`]
    fn nontrival_permits(&self) -> impl Iterator<Item = Policy> + '_ {
        self.residual_permits
            .iter()
            .map(|(id, (expr, annotations))| {
                construct_policy((Effect::Permit, id, expr, annotations))
            })
    }

    /// Returns the set of non-trivial (meaning more than just `true` or `false`) residuals expressions from [`Effect::Forbid`]
    pub fn nontrival_forbids(&self) -> impl Iterator<Item = Policy> + '_ {
        self.residual_forbids
            .iter()
            .map(|(id, (expr, annotations))| {
                construct_policy((Effect::Forbid, id, expr, annotations))
            })
    }

    /// Returns every policy residual, including trivial ones
    pub fn all_residuals(&'_ self) -> impl Iterator<Item = Policy> + '_ {
        self.all_permit_residuals()
            .chain(self.all_forbid_residuals())
            .map(construct_policy)
    }

    /// Returns all residuals expressions that come from [`Effect::Permit`] policies
    fn all_permit_residuals(&'_ self) -> impl Iterator<Item = PolicyComponents<'_>> {
        let trues = self
            .satisfied_permits
            .iter()
            .map(|(id, a)| (id, (&self.true_expr, a)));
        let falses = self
            .false_permits
            .iter()
            .map(|(id, (_, a))| (id, (&self.false_expr, a)));
        let nontrivial = self
            .residual_permits
            .iter()
            .map(|(id, (r, a))| (id, (r, a)));
        trues
            .chain(falses)
            .chain(nontrivial)
            .map(|(id, (r, a))| (Effect::Permit, id, r, a))
    }

    /// Returns all residuals expressions that come from [`Effect::Forbid`] policies
    fn all_forbid_residuals(&'_ self) -> impl Iterator<Item = PolicyComponents<'_>> {
        let trues = self
            .satisfied_forbids
            .iter()
            .map(|(id, a)| (id, (&self.true_expr, a)));
        let falses = self
            .false_forbids
            .iter()
            .map(|(id, (_, a))| (id, (&self.false_expr, a)));
        let nontrivial = self
            .residual_forbids
            .iter()
            .map(|(id, (r, a))| (id, (r, a)));
        trues
            .chain(falses)
            .chain(nontrivial)
            .map(|(id, (r, a))| (Effect::Forbid, id, r, a))
    }

    /// Return the residual for a given [`PolicyID`], if it exists in the response
    pub fn get(&self, id: &PolicyID) -> Option<Policy> {
        self.get_permit(id).or_else(|| self.get_forbid(id))
    }

    fn get_permit(&self, id: &PolicyID) -> Option<Policy> {
        self.residual_permits
            .get(id)
            .map(|(a, b)| (a, b))
            .or_else(|| self.satisfied_permits.get(id).map(|a| (&self.true_expr, a)))
            .or_else(|| {
                self.false_permits
                    .get(id)
                    .map(|(_, a)| (&self.false_expr, a))
            })
            .map(|(expr, a)| construct_policy((Effect::Permit, id, expr, a)))
    }

    fn get_forbid(&self, id: &PolicyID) -> Option<Policy> {
        self.residual_forbids
            .get(id)
            .map(|(a, b)| (a, b))
            .or_else(|| self.satisfied_forbids.get(id).map(|a| (&self.true_expr, a)))
            .or_else(|| {
                self.false_forbids
                    .get(id)
                    .map(|(_, a)| (&self.false_expr, a))
            })
            .map(|(expr, a)| construct_policy((Effect::Forbid, id, expr, a)))
    }

    /// Attempt to re-authorize this response given a mapping from unknowns to values
    pub fn reauthorize(
        &self,
        mapping: &HashMap<SmolStr, Value>,
        auth: &Authorizer,
        es: &Entities,
    ) -> Result<Self, ReauthorizationError> {
        let policyset = self.all_policies(mapping)?;
        let new_request = self.concretize_request(mapping)?;
        Ok(auth.is_authorized_core(new_request, &policyset, es))
    }

    fn all_policies(&self, mapping: &HashMap<SmolStr, Value>) -> Result<PolicySet, PolicySetError> {
        let mapper = map_unknowns(mapping);
        PolicySet::try_from_iter(
            self.all_permit_residuals()
                .chain(self.all_forbid_residuals())
                .map(mapper),
        )
    }

    fn concretize_request(
        &self,
        mapping: &HashMap<SmolStr, Value>,
    ) -> Result<Request, ConcretizationError> {
        let mut context = self.request.context.clone();

        let principal = self.request.principal().concretize("principal", mapping)?;

        let action = self.request.action.concretize("action", mapping)?;

        let resource = self.request.resource.concretize("resource", mapping)?;

        if let Some((key, val)) = mapping.get_key_value("context") {
            if let Ok(attrs) = val.get_as_record() {
                match self.request.context() {
                    Some(ctx) => {
                        return Err(ConcretizationError::VarConfictError {
                            id: key.to_owned(),
                            existing_value: ctx.clone().into(),
                            given_value: val.clone(),
                        });
                    }
                    None => context = Some(Context::Value(attrs.clone())),
                }
            } else {
                return Err(ConcretizationError::ValueError {
                    id: key.to_owned(),
                    expected_type: "record",
                    given_value: val.to_owned(),
                });
            }
        }

        // We need to replace unknowns in the partial context as well
        context = context
            .map(|context| context.substitute(mapping))
            .transpose()?;

        Ok(Request {
            principal,
            action,
            resource,
            context,
        })
    }

    fn errors(self) -> impl Iterator<Item = AuthorizationError> {
        self.residual_forbids
            .into_iter()
            .chain(self.residual_permits)
            .map(
                |(id, (expr, _))| AuthorizationError::PolicyEvaluationError {
                    id,
                    error: EvaluationError::non_value(expr.as_ref().clone()),
                },
            )
            .chain(self.errors)
            .collect::<Vec<_>>()
            .into_iter()
    }
}

impl EntityUIDEntry {
    fn concretize(
        &self,
        key: &str,
        mapping: &HashMap<SmolStr, Value>,
    ) -> Result<Self, ConcretizationError> {
        if let Some(val) = mapping.get(key) {
            if let Ok(uid) = val.get_as_entity() {
                match self {
                    EntityUIDEntry::Known { euid, .. } => {
                        Err(ConcretizationError::VarConfictError {
                            id: key.into(),
                            existing_value: euid.as_ref().clone().into(),
                            given_value: val.clone(),
                        })
                    }
                    EntityUIDEntry::Unknown { ty: None, .. } => {
                        Ok(EntityUIDEntry::known(uid.clone(), None))
                    }
                    EntityUIDEntry::Unknown {
                        ty: Some(type_of_unknown),
                        ..
                    } => {
                        if type_of_unknown == uid.entity_type() {
                            Ok(EntityUIDEntry::known(uid.clone(), None))
                        } else {
                            Err(ConcretizationError::EntityTypeConfictError {
                                id: key.into(),
                                existing_value: type_of_unknown.clone(),
                                given_value: val.to_owned(),
                            })
                        }
                    }
                }
            } else {
                Err(ConcretizationError::ValueError {
                    id: key.into(),
                    expected_type: "entity",
                    given_value: val.to_owned(),
                })
            }
        } else {
            Ok(self.clone())
        }
    }
}

impl From<PartialResponse> for Response {
    fn from(p: PartialResponse) -> Self {
        let decision = if !p.satisfied_permits.is_empty() && p.satisfied_forbids.is_empty() {
            Decision::Allow
        } else {
            Decision::Deny
        };
        Response::new(
            decision,
            p.must_be_determining().map(|p| p.id().clone()).collect(),
            p.errors().collect(),
        )
    }
}

/// Build a policy from a policy components
fn construct_policy((effect, id, expr, annotations): PolicyComponents<'_>) -> Policy {
    Policy::from_when_clause_annos(
        effect,
        expr.clone(),
        id.clone(),
        expr.source_loc().cloned(),
        (*annotations).clone(),
    )
}

/// Given a mapping from unknown names to values and a policy prototype
/// substitute the residual with the mapping and build a policy.
/// Curried for convenience
fn map_unknowns<'a>(
    mapping: &'a HashMap<SmolStr, Value>,
) -> impl Fn(PolicyComponents<'a>) -> Policy {
    |(effect, id, expr, annotations)| {
        Policy::from_when_clause_annos(
            effect,
            Arc::new(expr.substitute(mapping)),
            id.clone(),
            expr.source_loc().cloned(),
            annotations.clone(),
        )
    }
}

/// Checks if a given residual record did error, returning the [`PolicyID`] if it did
fn did_error<'a>(
    (id, (state, _)): (&'a PolicyID, &'_ (ErrorState, Arc<Annotations>)),
) -> Option<&'a PolicyID> {
    match *state {
        ErrorState::NoError => None,
        ErrorState::Error => Some(id),
    }
}

#[cfg(test)]
// PANIC SAFETY testing
#[allow(clippy::indexing_slicing)]
mod test {
    use std::{
        collections::HashSet,
        iter::{empty, once},
    };

    // An extremely slow and bad set, but it only requires that the contents be [`PartialEq`]
    // Using this because I don't want to enforce an output order on the tests, but policies can't easily be Hash or Ord
    #[derive(Debug, Default)]
    struct SlowSet<T> {
        contents: Vec<T>,
    }

    impl<T: PartialEq> SlowSet<T> {
        pub fn from(iter: impl IntoIterator<Item = T>) -> Self {
            let mut contents = vec![];
            for item in iter.into_iter() {
                if !contents.contains(&item) {
                    contents.push(item)
                }
            }
            Self { contents }
        }

        pub fn len(&self) -> usize {
            self.contents.len()
        }

        pub fn contains(&self, item: &T) -> bool {
            self.contents.contains(item)
        }
    }

    impl<T: PartialEq> PartialEq for SlowSet<T> {
        fn eq(&self, rhs: &Self) -> bool {
            if self.len() == rhs.len() {
                self.contents.iter().all(|item| rhs.contains(item))
            } else {
                false
            }
        }
    }

    impl<T: PartialEq> FromIterator<T> for SlowSet<T> {
        fn from_iter<I>(iter: I) -> Self
        where
            I: IntoIterator<Item = T>,
        {
            Self::from(iter)
        }
    }

    use crate::{
        authorizer::{
            ActionConstraint, EntityUID, PrincipalConstraint, ResourceConstraint, RestrictedExpr,
            Unknown,
        },
        extensions::Extensions,
        parser::parse_policyset,
        FromNormalizedStr,
    };

    use super::*;

    #[test]
    fn sanity_check() {
        let empty_annotations: Arc<Annotations> = Arc::default();
        let one_plus_two = Arc::new(Expr::add(Expr::val(1), Expr::val(2)));
        let three_plus_four = Arc::new(Expr::add(Expr::val(3), Expr::val(4)));
        let a = once((PolicyID::from_string("a"), empty_annotations.clone()));
        let bc = [
            (
                PolicyID::from_string("b"),
                (ErrorState::Error, empty_annotations.clone()),
            ),
            (
                PolicyID::from_string("c"),
                (ErrorState::NoError, empty_annotations.clone()),
            ),
        ];
        let d = once((
            PolicyID::from_string("d"),
            (one_plus_two.clone(), empty_annotations.clone()),
        ));
        let e = once((PolicyID::from_string("e"), empty_annotations.clone()));
        let fg = [
            (
                PolicyID::from_string("f"),
                (ErrorState::Error, empty_annotations.clone()),
            ),
            (
                PolicyID::from_string("g"),
                (ErrorState::NoError, empty_annotations.clone()),
            ),
        ];
        let h = once((
            PolicyID::from_string("h"),
            (three_plus_four.clone(), empty_annotations),
        ));
        let errs = empty();
        let pr = PartialResponse::new(
            a,
            bc,
            d,
            e,
            fg,
            h,
            errs,
            Arc::new(Request::new_unchecked(
                EntityUIDEntry::unknown(),
                EntityUIDEntry::unknown(),
                EntityUIDEntry::unknown(),
                Some(Context::empty()),
            )),
        );

        let a = Policy::from_when_clause(
            Effect::Permit,
            Expr::val(true),
            PolicyID::from_string("a"),
            None,
        );
        let b = Policy::from_when_clause(
            Effect::Permit,
            Expr::val(false),
            PolicyID::from_string("b"),
            None,
        );
        let c = Policy::from_when_clause(
            Effect::Permit,
            Expr::val(false),
            PolicyID::from_string("c"),
            None,
        );
        let d = Policy::from_when_clause_annos(
            Effect::Permit,
            one_plus_two,
            PolicyID::from_string("d"),
            None,
            Arc::default(),
        );
        let e = Policy::from_when_clause(
            Effect::Forbid,
            Expr::val(true),
            PolicyID::from_string("e"),
            None,
        );
        let f = Policy::from_when_clause(
            Effect::Forbid,
            Expr::val(false),
            PolicyID::from_string("f"),
            None,
        );
        let g = Policy::from_when_clause(
            Effect::Forbid,
            Expr::val(false),
            PolicyID::from_string("g"),
            None,
        );
        let h = Policy::from_when_clause_annos(
            Effect::Forbid,
            three_plus_four,
            PolicyID::from_string("h"),
            None,
            Arc::default(),
        );

        assert_eq!(
            pr.definitely_satisfied_permits().collect::<SlowSet<_>>(),
            SlowSet::from([a.clone()])
        );
        assert_eq!(
            pr.definitely_satisfied_forbids().collect::<SlowSet<_>>(),
            SlowSet::from([e.clone()])
        );
        assert_eq!(
            pr.definitely_satisfied().collect::<SlowSet<_>>(),
            SlowSet::from([a.clone(), e.clone()])
        );
        assert_eq!(
            pr.definitely_errored().collect::<HashSet<_>>(),
            HashSet::from([&PolicyID::from_string("b"), &PolicyID::from_string("f")])
        );
        assert_eq!(
            pr.may_be_determining().collect::<SlowSet<_>>(),
            SlowSet::from([e.clone(), h.clone()])
        );
        assert_eq!(
            pr.must_be_determining().collect::<SlowSet<_>>(),
            SlowSet::from([e.clone()])
        );
        assert_eq!(pr.nontrivial_residuals().count(), 2);

        assert_eq!(
            pr.nontrivial_residuals().collect::<SlowSet<_>>(),
            SlowSet::from([d.clone(), h.clone()])
        );
        assert_eq!(
            pr.all_residuals().collect::<SlowSet<_>>(),
            SlowSet::from([&a, &b, &c, &d, &e, &f, &g, &h].into_iter().cloned())
        );
        assert_eq!(
            pr.nontrivial_residual_ids().collect::<HashSet<_>>(),
            HashSet::from([&PolicyID::from_string("d"), &PolicyID::from_string("h")])
        );

        assert_eq!(pr.get(&PolicyID::from_string("a")), Some(a));
        assert_eq!(pr.get(&PolicyID::from_string("b")), Some(b));
        assert_eq!(pr.get(&PolicyID::from_string("c")), Some(c));
        assert_eq!(pr.get(&PolicyID::from_string("d")), Some(d));
        assert_eq!(pr.get(&PolicyID::from_string("e")), Some(e));
        assert_eq!(pr.get(&PolicyID::from_string("f")), Some(f));
        assert_eq!(pr.get(&PolicyID::from_string("g")), Some(g));
        assert_eq!(pr.get(&PolicyID::from_string("h")), Some(h));
        assert_eq!(pr.get(&PolicyID::from_string("i")), None);
    }

    #[test]
    fn build_policies_trivial_permit() {
        let e = Arc::new(Expr::add(Expr::val(1), Expr::val(2)));
        let id = PolicyID::from_string("foo");
        let p = construct_policy((Effect::Permit, &id, &e, &Arc::default()));
        assert_eq!(p.effect(), Effect::Permit);
        assert!(p.annotations().next().is_none());
        assert_eq!(p.action_constraint(), &ActionConstraint::Any);
        assert_eq!(p.principal_constraint(), PrincipalConstraint::any());
        assert_eq!(p.resource_constraint(), ResourceConstraint::any());
        assert_eq!(p.id(), &id);
        assert_eq!(p.non_scope_constraints(), e.as_ref());
    }

    #[test]
    fn build_policies_trivial_forbid() {
        let e = Arc::new(Expr::add(Expr::val(1), Expr::val(2)));
        let id = PolicyID::from_string("foo");
        let p = construct_policy((Effect::Forbid, &id, &e, &Arc::default()));
        assert_eq!(p.effect(), Effect::Forbid);
        assert!(p.annotations().next().is_none());
        assert_eq!(p.action_constraint(), &ActionConstraint::Any);
        assert_eq!(p.principal_constraint(), PrincipalConstraint::any());
        assert_eq!(p.resource_constraint(), ResourceConstraint::any());
        assert_eq!(p.id(), &id);
        assert_eq!(p.non_scope_constraints(), e.as_ref());
    }

    #[test]
    fn did_error_error() {
        assert_eq!(
            did_error((
                &PolicyID::from_string("foo"),
                &(ErrorState::Error, Arc::default())
            )),
            Some(&PolicyID::from_string("foo"))
        );
    }

    #[test]
    fn did_error_noerror() {
        assert_eq!(
            did_error((
                &PolicyID::from_string("foo"),
                &(ErrorState::NoError, Arc::default())
            )),
            None,
        );
    }

    #[test]
    fn reauthorize() {
        let policies = parse_policyset(
            r#"
            permit(principal, action, resource) when {
                principal == NS::"a" && resource == NS::"b"
            };
            forbid(principal, action, resource) when {
                context.b
            };
        "#,
        )
        .unwrap();

        let context_unknown = Context::from_pairs(
            std::iter::once((
                "b".into(),
                RestrictedExpr::unknown(Unknown::new_untyped("b")),
            )),
            Extensions::all_available(),
        )
        .unwrap();

        let partial_request = Request {
            principal: EntityUIDEntry::known(r#"NS::"a""#.parse().unwrap(), None),
            action: EntityUIDEntry::unknown(),
            resource: EntityUIDEntry::unknown(),
            context: Some(context_unknown),
        };

        let entities = Entities::new();

        let authorizer = Authorizer::new();
        let partial_response = authorizer.is_authorized_core(partial_request, &policies, &entities);

        let response_with_concrete_resource = partial_response
            .reauthorize(
                &HashMap::from_iter(std::iter::once((
                    "resource".into(),
                    EntityUID::from_normalized_str(r#"NS::"b""#).unwrap().into(),
                ))),
                &authorizer,
                &entities,
            )
            .unwrap();

        assert_eq!(
            response_with_concrete_resource
                .definitely_satisfied()
                .next()
                .unwrap()
                .effect(),
            Effect::Permit
        );

        let response_with_concrete_context_attr = response_with_concrete_resource
            .reauthorize(
                &HashMap::from_iter(std::iter::once(("b".into(), true.into()))),
                &authorizer,
                &entities,
            )
            .unwrap();

        assert_eq!(
            response_with_concrete_context_attr.decision(),
            Some(Decision::Deny)
        );
    }
}