gatehouse 0.6.0

An in-process authorization engine for Rust with composable policies and request-scoped fact loading.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
use crate::{FactLoadErrorKind, FactLoadResult};
use std::borrow::Cow;
use std::fmt;

/// The type of boolean combining operation a policy might represent.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
#[cfg_attr(feature = "serde", serde(rename_all = "snake_case"))]
#[non_exhaustive]
pub enum CombineOp {
    /// All inner policies must grant access.
    And,
    /// At least one inner policy must grant access.
    Or,
    /// The inner policy's decision is inverted.
    Not,
    /// A parent policy delegated the decision to another checker.
    Delegate,
    /// Any forbidding policy denies; otherwise at least one policy must
    /// grant. The root operation of [`crate::PermissionChecker`].
    DenyOverrides,
}

impl fmt::Display for CombineOp {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            CombineOp::And => write!(f, "AND"),
            CombineOp::Or => write!(f, "OR"),
            CombineOp::Not => write!(f, "NOT"),
            CombineOp::Delegate => write!(f, "DELEGATE"),
            CombineOp::DenyOverrides => write!(f, "DENY_OVERRIDES"),
        }
    }
}

/// The decision carried by one node of a [`PolicyEvalResult`] tree.
///
/// Every node — leaf and combinator alike — carries exactly one `Decision`,
/// exposed through [`PolicyEvalResult::decision`]. Leaves map 1:1 onto their
/// variant; [`PolicyEvalResult::Combined`] stores the decision produced by its
/// combining rule, so callers never need to re-derive an aggregate outcome
/// from the children.
///
/// `Indeterminate` is the fail-closed "could not evaluate" decision: the node
/// consulted an input (typically a fact load) that was unavailable. It never
/// grants, and inside [`crate::PermissionChecker`] an `Indeterminate` from a
/// veto policy also blocks grants, because the failed policy might have
/// forbidden the request.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
#[cfg_attr(feature = "serde", serde(rename_all = "snake_case"))]
#[non_exhaustive]
pub enum Decision {
    /// The node grants access.
    Grant,
    /// The node neither grants nor forbids.
    NotApplicable,
    /// The node actively forbids access.
    Forbid,
    /// The node consulted an input that was unavailable and could not
    /// decide. Fail-closed: never treated as a grant.
    Indeterminate,
}

impl fmt::Display for Decision {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Grant => write!(f, "GRANT"),
            Self::NotApplicable => write!(f, "NOT_APPLICABLE"),
            Self::Forbid => write!(f, "FORBID"),
            Self::Indeterminate => write!(f, "INDETERMINATE"),
        }
    }
}

/// How a fact load that informed a policy decision resolved.
///
/// This mirrors [`crate::FactLoadResult`] without its value type, so it can be
/// recorded on the non-generic [`PolicyEvalResult`] tree and serialized into
/// audit logs. The concrete value (for example the `bool` of a relationship
/// check) is reflected by the grant/deny outcome and the node's reason, not by
/// this enum.
#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
#[cfg_attr(feature = "serde", serde(rename_all = "snake_case"))]
#[non_exhaustive]
pub enum FactOutcome {
    /// The fact existed.
    Found,
    /// The fact source was reached, but had no value for the key.
    Missing,
    /// The fact load failed.
    Error,
}

impl FactOutcome {
    /// Classifies a [`crate::FactLoadResult`] into the value-erased outcome.
    pub fn from_load_result<V>(result: &crate::FactLoadResult<V>) -> Self {
        match result {
            crate::FactLoadResult::Found(_) => Self::Found,
            crate::FactLoadResult::Missing => Self::Missing,
            crate::FactLoadResult::Error(_) => Self::Error,
        }
    }
}

impl fmt::Display for FactOutcome {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Found => write!(f, "found"),
            Self::Missing => write!(f, "missing"),
            Self::Error => write!(f, "error"),
        }
    }
}

/// A record that a policy consulted a fact while reaching its decision.
///
/// Fact-backed policies (such as [`crate::RebacPolicy`]) attach one of these per
/// fact lookup to their [`PolicyEvalResult::Granted`] or
/// [`PolicyEvalResult::NotApplicable`] node, so a decision's *inputs* are explained
/// alongside its outcome. Provenance is intentionally type-erased — a fact
/// name, a rendered key, an outcome, and optional detail — rather than the
/// typed [`crate::FactKey`], so it lives on the non-generic result tree and is
/// straightforward to log.
///
/// Operational fact-load telemetry (latencies, batch fan-out, cache hits) is a
/// separate concern surfaced through `tracing` spans (`gatehouse.fact_load`);
/// this type is for per-decision explanation.
#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
pub struct FactProvenance {
    /// The [`crate::FactKey::NAME`] of the consulted fact (e.g. `"relationship"`).
    pub fact_name: &'static str,
    /// A human-readable rendering of the fact key that was looked up.
    pub key: String,
    /// How the load resolved.
    pub outcome: FactOutcome,
    /// Optional extra detail. For [`FactOutcome::Error`] recorded through
    /// [`Self::from_load_result`], this is
    /// [`crate::FactLoadError::audit_detail`], which withholds backend error
    /// messages that were not written for audit output.
    pub detail: Option<String>,
    /// Machine-readable classification when this provenance records a fact
    /// load error.
    #[cfg_attr(feature = "serde", serde(skip_serializing_if = "Option::is_none"))]
    pub error_kind: Option<FactLoadErrorKind>,
}

impl FactProvenance {
    /// Records a consulted fact from manually supplied parts.
    ///
    /// Prefer [`Self::from_load_result`] when a [`FactLoadResult`] is
    /// available. Manually constructing [`FactOutcome::Error`] through this
    /// method produces unclassified error provenance, so
    /// [`Self::error_kind`] is `None`.
    pub fn new(
        fact_name: &'static str,
        key: impl Into<String>,
        outcome: FactOutcome,
        detail: Option<String>,
    ) -> Self {
        Self {
            fact_name,
            key: key.into(),
            outcome,
            detail,
            error_kind: None,
        }
    }

    /// Records a consulted fact directly from its load result.
    ///
    /// This is the canonical constructor for fact-backed policies. It records
    /// the value-erased [`FactOutcome`], preserves a structured
    /// [`FactLoadErrorKind`], and records
    /// [`crate::FactLoadError::audit_detail`] into [`Self::detail`] without
    /// requiring every policy to repeat that mapping by hand.
    pub fn from_load_result<V>(
        fact_name: &'static str,
        key: impl Into<String>,
        result: &FactLoadResult<V>,
    ) -> Self {
        let (detail, error_kind) = match result {
            FactLoadResult::Error(error) => {
                (Some(error.audit_detail().into_owned()), Some(error.kind()))
            }
            FactLoadResult::Found(_) | FactLoadResult::Missing => (None, None),
        };

        Self {
            fact_name,
            key: key.into(),
            outcome: FactOutcome::from_load_result(result),
            detail,
            error_kind,
        }
    }
}

impl fmt::Display for FactProvenance {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            f,
            "fact {} [{}]: {}",
            self.fact_name, self.outcome, self.key
        )?;
        if let Some(detail) = &self.detail {
            write!(f, " ({detail})")?;
        }
        Ok(())
    }
}

/// The inspectable audit representation of a policy decision or aggregate.
///
/// Policies return [`crate::GrantResult`] or [`crate::VetoResult`], whose
/// constructors preserve capability boundaries. This public enum supports
/// inspection, formatting, and serialization; constructing a raw tree does not
/// grant authority and it cannot be converted into a typed policy result.
///
/// - [`PolicyEvalResult::Granted`]: Indicates that access is granted, with an optional reason.
/// - [`PolicyEvalResult::NotApplicable`]: Indicates the policy did not grant access — either its
///   predicate did not match (the policy is not applicable to this request) or it simply
///   has nothing positive to say. `NotApplicable` from one policy never overrides a sibling's grant.
/// - [`PolicyEvalResult::Forbidden`]: Indicates the policy **actively forbids** this request.
///   Inside a [`crate::PermissionChecker`] a forbid overrides every grant (deny-overrides
///   semantics). Produced by [`crate::PolicyBuilder::build_veto`] policies
///   whose predicates match, or custom [`crate::VetoPolicy`] implementations.
/// - [`PolicyEvalResult::Combined`]: Represents the aggregate result of combining multiple policies.
#[derive(Debug, Clone)]
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
#[cfg_attr(feature = "serde", serde(rename_all = "snake_case"))]
#[non_exhaustive]
pub enum PolicyEvalResult {
    /// Access granted. Contains the policy type and an optional reason.
    Granted {
        /// The name of the policy that granted access.
        ///
        /// `Cow<'static, str>` so static policy names (the common case)
        /// pass through with zero allocation; dynamic names still work via
        /// `Cow::Owned`.
        policy_type: Cow<'static, str>,
        /// An optional human-readable reason for the grant.
        reason: Option<String>,
        /// Facts the policy consulted to reach this decision. Empty for
        /// policies that are not fact-backed.
        provenance: Vec<FactProvenance>,
    },
    /// Policy did not apply. Contains the policy type and a reason.
    NotApplicable {
        /// The name of the policy that did not apply.
        policy_type: Cow<'static, str>,
        /// A human-readable reason why this policy did not grant.
        reason: String,
        /// Facts the policy consulted to reach this decision. Empty for
        /// policies that are not fact-backed.
        provenance: Vec<FactProvenance>,
    },
    /// Access actively forbidden: the policy matched and vetoes this request.
    ///
    /// Unlike [`PolicyEvalResult::NotApplicable`] ("this policy does not grant"),
    /// `Forbidden` means "this policy forbids". [`crate::PermissionChecker`]
    /// honors a forbid over any grant from sibling policies, including forbids
    /// nested inside combinator results.
    Forbidden {
        /// The name of the policy that forbids access.
        policy_type: Cow<'static, str>,
        /// A human-readable reason for the veto.
        reason: String,
        /// Facts the policy consulted to reach this decision. Empty for
        /// policies that are not fact-backed.
        provenance: Vec<FactProvenance>,
    },
    /// The policy could not be evaluated because an input it needed was
    /// unavailable — typically a fact that failed to load.
    ///
    /// Fail-closed: an indeterminate policy never grants. Unlike
    /// [`PolicyEvalResult::NotApplicable`] ("this policy does not grant"),
    /// `Indeterminate` means "this policy might have granted or forbidden,
    /// but its inputs were unavailable". [`crate::PermissionChecker`] blocks
    /// grants when a veto policy is indeterminate, and surfaces the
    /// failure as [`AccessEvaluation::Indeterminate`] so callers can map an
    /// authorization-data outage to a 5xx instead of a 403.
    Indeterminate {
        /// The name of the policy that could not be evaluated.
        policy_type: Cow<'static, str>,
        /// A human-readable reason describing the unavailable input.
        reason: String,
        /// Facts the policy consulted to reach this decision. By convention
        /// at least one entry has [`FactOutcome::Error`], though custom
        /// policies may leave this empty and explain via `reason`.
        provenance: Vec<FactProvenance>,
    },
    /// Combined result from multiple policy evaluations.
    /// Contains the policy type, the combining operation ([`CombineOp`]),
    /// a list of child evaluation results, and the aggregate decision.
    Combined {
        /// The aggregate's name: a combinator's type name (e.g.
        /// `"AndPolicy"`) or the name given with `named`, a delegate's name,
        /// or the checker root's name.
        policy_type: Cow<'static, str>,
        /// The boolean operation used to combine child results.
        operation: CombineOp,
        /// The individual results from each child policy.
        children: Vec<PolicyEvalResult>,
        /// The aggregate decision after applying the combining operation.
        decision: Decision,
        /// Facts consulted directly by this aggregate policy.
        provenance: Vec<FactProvenance>,
    },
}

/// The complete result of a permission evaluation.
/// Contains both the final decision and a detailed trace for debugging.
///
/// ### Evaluation Tracing
///
/// The permission system provides detailed tracing of policy decisions:
/// ```rust
/// # use gatehouse::*;
/// # use uuid::Uuid;
/// #
/// # // Define simple types for the example
/// # #[derive(Debug, Clone)]
/// # struct User { id: Uuid }
/// # #[derive(Debug, Clone)]
/// # struct Document { id: Uuid }
/// # #[derive(Debug, Clone)]
/// # struct ReadAction;
/// # #[derive(Debug, Clone)]
/// # struct EmptyContext;
/// #
/// # async fn example() -> AccessEvaluation {
/// #     struct Documents;
/// #     impl PolicyDomain for Documents {
/// #         type Subject = User;
/// #         type Action = ReadAction;
/// #         type Resource = Document;
/// #         type Context = EmptyContext;
/// #     }
/// #     let checker = PermissionChecker::<Documents>::new();
/// #     let user = User { id: Uuid::new_v4() };
/// #     let document = Document { id: Uuid::new_v4() };
/// #     let session = EvaluationSession::empty();
/// #     checker.bind(&session, &user, &ReadAction, &EmptyContext).check(&document).await
/// # }
/// #
/// # tokio_test::block_on(async {
/// let result = example().await;
///
/// match result {
///     AccessEvaluation::Granted { policy_type, reason, trace, .. } => {
///         println!("Access granted by {}: {:?}", policy_type, reason);
///         println!("Full evaluation trace:\n{}", trace.format());
///     }
///     AccessEvaluation::Denied { reason, trace, .. } => {
///         println!("Access denied: {}", reason);
///         println!("Full evaluation trace:\n{}", trace.format());
///     }
///     AccessEvaluation::Indeterminate { reason, trace, .. } => {
///         println!("Could not evaluate access: {}", reason);
///         println!("Full evaluation trace:\n{}", trace.format());
///     }
///     _ => {
///         println!("Access denied: unknown decision variant");
///     }
/// }
/// # });
/// ```
///
/// ### Decisions come only from evaluation
///
/// The variants of `AccessEvaluation` and [`AccessError`], and the
/// [`FilterError`] and [`crate::LookupAuthorizedPage`] structs, are
/// `#[non_exhaustive]`. Code outside this crate can read and match them but
/// cannot construct them, so each value was produced by a
/// [`crate::PermissionChecker`] evaluating policies. This is a statement
/// about provenance, not trust: the policies may be anything, and the owner
/// of a value can still write to its public fields.
///
/// ```compile_fail,E0639
/// use gatehouse::{AccessEvaluation, EvalTrace};
/// let forged = AccessEvaluation::Granted {
///     policy_type: "Forged".into(),
///     reason: None,
///     trace: EvalTrace::new(),
/// };
/// ```
///
/// ```compile_fail,E0639
/// use gatehouse::{AccessError, EvalTrace};
/// let forged = AccessError::Denied {
///     reason: "forged".into(),
///     trace: EvalTrace::new(),
/// };
/// ```
///
/// ```compile_fail,E0639
/// let forged = gatehouse::LookupAuthorizedPage::<u32> {
///     resources: vec![1],
///     next_cursor: None,
/// };
/// ```
///
/// ```compile_fail,E0639
/// let forged = gatehouse::FilterError::<u32> { evaluations: Vec::new() };
/// ```
#[derive(Debug, Clone)]
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
#[cfg_attr(feature = "serde", serde(rename_all = "snake_case"))]
#[non_exhaustive]
#[must_use = "inspect the authorization decision or propagate it with into_result()?"]
pub enum AccessEvaluation {
    /// Access was granted.
    #[non_exhaustive]
    Granted {
        /// The policy that decided the grant; see
        /// [`AccessEvaluation::granted_policy_type`]. `Cow<'static, str>` for the
        /// same reason as on [`PolicyEvalResult`]: static names pass
        /// through with zero allocation.
        policy_type: Cow<'static, str>,
        /// Optional reason for granting
        reason: Option<String>,
        /// Full evaluation trace including any rejected policies
        trace: EvalTrace,
    },
    /// Access was denied.
    #[non_exhaustive]
    Denied {
        /// The complete evaluation trace showing all policy decisions
        trace: EvalTrace,
        /// Summary reason for denial
        reason: String,
    },
    /// The evaluation could not reach a decision: a policy that mattered was
    /// [`PolicyEvalResult::Indeterminate`] and no veto fired.
    ///
    /// Fail-closed: this is never a grant. It is distinct from
    /// [`AccessEvaluation::Denied`] so callers can map "authorization inputs
    /// were unavailable" (usually a 5xx and a retry) differently from "the
    /// policies decided against this request" (a 403). Produced when a
    /// veto policy was indeterminate (its potential veto is unresolved, so a
    /// grant cannot be released), or when no policy granted and at least one
    /// grant policy was indeterminate (it might have granted).
    ///
    /// The classified fact-load failures are in the trace; use
    /// [`Self::fact_load_errors`] to collect them and
    /// [`FactProvenance::error_kind`] to distinguish transient backend
    /// failures from permanent wiring bugs.
    #[non_exhaustive]
    Indeterminate {
        /// The complete evaluation trace showing all policy decisions
        trace: EvalTrace,
        /// Summary reason naming the policy that could not be evaluated
        reason: String,
    },
}

/// A non-grant decision with its full audit evidence.
#[derive(Debug, Clone)]
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
#[non_exhaustive]
pub enum AccessError {
    /// Authorization completed and denied access.
    #[non_exhaustive]
    Denied {
        /// Summary reason for the denial.
        reason: String,
        /// Complete evaluation evidence.
        trace: EvalTrace,
    },
    /// Authorization could not be decided.
    #[non_exhaustive]
    Indeterminate {
        /// Summary reason for the unresolved decision.
        reason: String,
        /// Complete evaluation evidence, including fact errors.
        trace: EvalTrace,
    },
}

impl AccessError {
    /// Returns the complete audit trace.
    pub fn trace(&self) -> &EvalTrace {
        match self {
            Self::Denied { trace, .. } | Self::Indeterminate { trace, .. } => trace,
        }
    }

    /// Returns all recorded fact failures, including failures in child policies.
    pub fn fact_load_errors(&self) -> Vec<&FactProvenance> {
        let mut errors = Vec::new();
        if let Some(root) = self.trace().root() {
            collect_fact_load_errors(root, &mut errors);
        }
        errors
    }
}

impl fmt::Display for AccessError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Denied { reason, .. } => write!(f, "access denied: {reason}"),
            Self::Indeterminate { reason, .. } => {
                write!(f, "authorization indeterminate: {reason}")
            }
        }
    }
}

impl std::error::Error for AccessError {}

/// An authorization batch containing at least one indeterminate decision.
///
/// No partial authorized list is returned. The original items and every
/// decision remain available in input order for inspection or recovery.
#[non_exhaustive]
pub struct FilterError<T> {
    /// All input items paired with their completed evaluations.
    pub evaluations: Vec<(T, AccessEvaluation)>,
}

impl<T> fmt::Debug for FilterError<T> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_map()
            .entries(
                self.evaluations
                    .iter()
                    .enumerate()
                    .map(|(index, (_, evaluation))| (index, evaluation)),
            )
            .finish()
    }
}

impl<T> FilterError<T> {
    /// Iterates over the original items whose authorization could not be decided.
    pub fn indeterminate(&self) -> impl Iterator<Item = (&T, &AccessEvaluation)> {
        self.evaluations
            .iter()
            .filter(|(_, evaluation)| evaluation.is_indeterminate())
            .map(|(item, evaluation)| (item, evaluation))
    }
}

impl<T> fmt::Display for FilterError<T> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str("could not determine authorization for every item")
    }
}

impl<T> std::error::Error for FilterError<T> {}

/// Walks a [`PolicyEvalResult`] tree looking for a `NotApplicable`
/// leaf whose `policy_type` equals `expected`. Used by
/// [`AccessEvaluation::assert_not_applicable_by`].
fn leaf_not_applicable_matches(node: &PolicyEvalResult, expected: &str) -> bool {
    match node {
        PolicyEvalResult::NotApplicable { policy_type, .. } => policy_type.as_ref() == expected,
        PolicyEvalResult::Granted { .. }
        | PolicyEvalResult::Forbidden { .. }
        | PolicyEvalResult::Indeterminate { .. } => false,
        PolicyEvalResult::Combined { children, .. } => children
            .iter()
            .any(|child| leaf_not_applicable_matches(child, expected)),
    }
}

/// Names the decisive spine of a checker-produced trace. Only a checker's
/// deny-overrides root is searched, so a hand-built trace attributes nothing.
fn decisive_path<'a, I>(trace: &'a EvalTrace, nodes: fn(&'a PolicyEvalResult) -> I) -> Vec<&'a str>
where
    I: Iterator<Item = &'a PolicyEvalResult>,
{
    match trace.root() {
        Some(
            root @ PolicyEvalResult::Combined {
                operation: CombineOp::DenyOverrides,
                ..
            },
        ) => nodes(root).map(PolicyEvalResult::policy_type).collect(),
        _ => Vec::new(),
    }
}

/// Collects every [`FactProvenance`] with [`FactOutcome::Error`] from a
/// result tree (leaves and combinator children).
fn collect_fact_load_errors<'a>(node: &'a PolicyEvalResult, out: &mut Vec<&'a FactProvenance>) {
    out.extend(
        node.provenance()
            .iter()
            .filter(|fact| fact.outcome == FactOutcome::Error),
    );
    if let PolicyEvalResult::Combined { children, .. } = node {
        for child in children {
            collect_fact_load_errors(child, out);
        }
    }
}

fn trace_has_fact_load_error(node: &PolicyEvalResult) -> bool {
    node.provenance()
        .iter()
        .any(|fact| fact.outcome == FactOutcome::Error)
        || matches!(node, PolicyEvalResult::Combined { children, .. } if children.iter().any(trace_has_fact_load_error))
}

impl AccessEvaluation {
    /// Whether access was granted
    pub fn is_granted(&self) -> bool {
        matches!(self, Self::Granted { .. })
    }

    /// Whether the evaluation was [`AccessEvaluation::Indeterminate`]:
    /// a non-grant caused by unavailable authorization inputs rather than
    /// by the policies deciding against the request.
    ///
    /// This is the structural, causal signal for mapping authorization
    /// infrastructure failures to a 5xx. Compare
    /// [`Self::denied_due_to_fact_load_error`], which is a coarser
    /// any-error-in-trace scan.
    pub fn is_indeterminate(&self) -> bool {
        matches!(self, Self::Indeterminate { .. })
    }

    /// Returns the evaluation trace regardless of outcome.
    ///
    /// Every variant carries an [`EvalTrace`]; this accessor saves callers
    /// the `match` when they only need the trace — typically to render it
    /// with [`EvalTrace::format`] for logs or debugging output.
    pub fn trace(&self) -> &EvalTrace {
        match self {
            Self::Granted { trace, .. }
            | Self::Denied { trace, .. }
            | Self::Indeterminate { trace, .. } => trace,
        }
    }

    /// Returns the name of the policy that decided a grant.
    ///
    /// This is the deciding policy, not necessarily the registered one: a
    /// grant through [`crate::OrPolicy`] or a delegate names the child that
    /// granted, while [`crate::AndPolicy`] and [`crate::NotPolicy`] are named
    /// themselves. [`Self::forbidden_by`] follows the same rule for vetoes.
    /// Use [`Self::grant_path`] for the chain the grant passed through; its
    /// first entry is the registered policy.
    ///
    /// Policy names are labels chosen by whoever built the policy. They are
    /// not unique, and a child checker behind a delegate can use the same
    /// name as a parent policy, so branch on names only where you control
    /// every policy that could produce them.
    pub fn granted_policy_type(&self) -> Option<&str> {
        match self {
            Self::Granted { policy_type, .. } => Some(policy_type),
            Self::Denied { .. } | Self::Indeterminate { .. } => None,
        }
    }

    /// Returns the policy names from the registered policy down to the one
    /// that decided a grant, outermost first. Empty for non-grants.
    ///
    /// The first entry is the policy registered with the checker, the last is
    /// [`Self::granted_policy_type`], and any between are the delegates and
    /// combinators the grant passed through. Checker roots, including the
    /// child checker inside a delegate, are omitted. The path ends at a
    /// conjunction ([`crate::AndPolicy`]) or inversion
    /// ([`crate::NotPolicy`]), which decides as a whole.
    pub fn grant_path(&self) -> Vec<&str> {
        match self {
            Self::Granted { trace, .. } => decisive_path(trace, PolicyEvalResult::grant_nodes),
            Self::Denied { .. } | Self::Indeterminate { .. } => Vec::new(),
        }
    }

    /// Returns the summary denial reason when the evaluation was a denial.
    ///
    /// Mirrors [`Self::granted_policy_type`] for the denied case. Returns
    /// `None` for [`AccessEvaluation::Indeterminate`]; use
    /// [`Self::indeterminate_reason`] for that variant.
    pub fn denied_reason(&self) -> Option<&str> {
        match self {
            Self::Denied { reason, .. } => Some(reason),
            Self::Granted { .. } | Self::Indeterminate { .. } => None,
        }
    }

    /// Returns the summary reason when the evaluation was
    /// [`AccessEvaluation::Indeterminate`].
    ///
    /// Mirrors [`Self::denied_reason`] for the indeterminate case.
    pub fn indeterminate_reason(&self) -> Option<&str> {
        match self {
            Self::Indeterminate { reason, .. } => Some(reason),
            Self::Granted { .. } | Self::Denied { .. } => None,
        }
    }

    /// Returns the name of the policy whose forbid caused this denial, if
    /// the denial was a deny-overrides veto rather than a plain
    /// "no policy granted" outcome.
    ///
    /// Useful for distinguishing "actively blocked" (suspension, legal
    /// hold) from "no grant matched" — for example to map the former to a
    /// distinct HTTP status or audit event. Returns `None` for grants and
    /// for ordinary denials.
    ///
    /// This names the policy that decided the veto. A veto through
    /// [`crate::AnyOfVeto`] or a delegate names the child that forbade;
    /// [`crate::AllOfVeto`] forbids only when every child does, so it is
    /// named itself. Use [`Self::forbidden_path`] for the full chain.
    pub fn forbidden_by(&self) -> Option<&str> {
        self.forbidden_path().last().copied()
    }

    /// Returns the policy names from the registered veto down to the one
    /// that decided it, outermost first. Empty unless a veto caused the
    /// denial.
    ///
    /// Mirrors [`Self::grant_path`]; [`Self::forbidden_by`] is the last entry.
    pub fn forbidden_path(&self) -> Vec<&str> {
        match self {
            // Grants have no veto; an indeterminate evaluation means no
            // forbid was observed (an observed forbid produces `Denied`).
            Self::Denied { trace, .. } => decisive_path(trace, PolicyEvalResult::forbid_nodes),
            Self::Granted { .. } | Self::Indeterminate { .. } => Vec::new(),
        }
    }

    /// Returns every fact provenance entry with [`FactOutcome::Error`]
    /// found anywhere in the evaluation trace.
    ///
    /// Empty for grants that never hit a load failure, and for denials
    /// whose consulted facts were only [`FactOutcome::Found`] or
    /// [`FactOutcome::Missing`]. Fact-backed policies (for example
    /// [`crate::RebacPolicy`]) attach load failures as provenance on their
    /// not-applicable leaves; this helper walks the whole tree so callers
    /// do not need to destructure combinators by hand.
    ///
    /// Use this when you need the error classification (via
    /// [`FactProvenance::error_kind`]) and audit-safe detail rather than a
    /// simple boolean — see
    /// [`Self::denied_due_to_fact_load_error`] for the yes/no form.
    pub fn fact_load_errors(&self) -> Vec<&FactProvenance> {
        let mut errors = Vec::new();
        if let Some(root) = self.trace().root() {
            collect_fact_load_errors(root, &mut errors);
        }
        errors
    }

    /// Returns `true` when this evaluation is a **non-grant** and at least
    /// one policy leaf in the trace consulted a fact that failed to load
    /// ([`FactOutcome::Error`]).
    ///
    /// Deprecated: use [`Self::is_indeterminate`]. Since the decision model
    /// gained a structural [`AccessEvaluation::Indeterminate`] variant,
    /// "could not evaluate" is a first-class, causal outcome:
    ///
    /// ```rust
    /// # use gatehouse::*;
    /// # fn handle(evaluation: AccessEvaluation) -> u16 {
    /// if evaluation.is_granted() {
    ///     200
    /// } else if evaluation.forbidden_by().is_some() {
    ///     403 // active veto — check before the infrastructure signal
    /// } else if evaluation.is_indeterminate() {
    ///     503 // authorization inputs unavailable — structural signal
    /// } else {
    ///     403
    /// }
    /// # }
    /// ```
    ///
    /// This helper remains an **any-error-in-trace** scan, not a causal
    /// check: it does not prove the load failure was the reason for the
    /// denial (a policy may record a load error yet deny for ordinary
    /// reasons). A settled aggregate may retain failed facts from an
    /// inconclusive child without itself being indeterminate. Use
    /// [`Self::fact_load_errors`] when you need the failed loads
    /// themselves.
    #[deprecated(
        since = "0.6.0",
        note = "use is_indeterminate() for the structural signal, or fact_load_errors() to inspect failed loads; this any-error-in-trace scan will be removed in 0.7"
    )]
    pub fn denied_due_to_fact_load_error(&self) -> bool {
        match self {
            Self::Denied { trace, .. } | Self::Indeterminate { trace, .. } => {
                trace.root().is_some_and(trace_has_fact_load_error)
            }
            Self::Granted { .. } => false,
        }
    }

    /// Test helper: panic unless the evaluation is `Granted` and the
    /// granting policy's name matches `expected`.
    ///
    /// Intended for policy unit tests that would otherwise hand-roll a
    /// pattern match over the evaluation. Prefer this over destructuring
    /// when the test's only assertion is "policy X granted access."
    ///
    /// ```rust
    /// # use gatehouse::*;
    /// # tokio_test::block_on(async {
    /// # struct Domain;
    /// # impl PolicyDomain for Domain {
    /// #     type Subject = ();
    /// #     type Action = ();
    /// #     type Resource = ();
    /// #     type Context = ();
    /// # }
    /// # let mut checker = PermissionChecker::<Domain>::new();
    /// # checker.add_policy(PolicyBuilder::<Domain>::new("AllowAll").allow_all());
    /// # let session = EvaluationSession::empty();
    /// # let evaluation = checker.bind(&session, &(), &(), &()).check(&()).await;
    /// evaluation.assert_granted_by("AllowAll");
    /// # });
    /// ```
    #[track_caller]
    pub fn assert_granted_by(&self, expected: &str) {
        match self {
            Self::Granted { policy_type, .. } => {
                assert_eq!(
                    policy_type.as_ref(),
                    expected,
                    "expected grant by policy `{expected}`, but the grant came from `{policy_type}`"
                );
            }
            Self::Denied { reason, .. } => {
                panic!("expected grant by policy `{expected}`, but access was denied: {reason}");
            }
            Self::Indeterminate { reason, .. } => {
                panic!(
                    "expected grant by policy `{expected}`, but the evaluation was \
                     indeterminate: {reason}"
                );
            }
        }
    }

    /// Test helper: panic unless the evaluation is `Denied`.
    ///
    /// An [`AccessEvaluation::Indeterminate`] outcome also panics: it is a
    /// non-grant, but it means the policies could not be evaluated rather
    /// than that they decided against the request. Use
    /// [`Self::assert_indeterminate`] for that case, and
    /// [`Self::assert_denied_with_reason_containing`] when you also
    /// need to assert on the denial reason.
    #[track_caller]
    pub fn assert_denied(&self) {
        match self {
            Self::Denied { .. } => {}
            Self::Granted {
                policy_type,
                reason,
                ..
            } => {
                panic!(
                    "expected denial, but access was granted by `{policy_type}`{}",
                    reason
                        .as_ref()
                        .map(|r| format!(": {r}"))
                        .unwrap_or_default()
                );
            }
            Self::Indeterminate { reason, .. } => {
                panic!("expected denial, but the evaluation was indeterminate: {reason}");
            }
        }
    }

    /// Test helper: panic unless the evaluation is
    /// [`AccessEvaluation::Indeterminate`].
    #[track_caller]
    pub fn assert_indeterminate(&self) {
        match self {
            Self::Indeterminate { .. } => {}
            Self::Granted { policy_type, .. } => {
                panic!(
                    "expected an indeterminate evaluation, but access was granted by \
                     `{policy_type}`"
                );
            }
            Self::Denied { reason, .. } => {
                panic!("expected an indeterminate evaluation, but access was denied: {reason}");
            }
        }
    }

    /// Test helper: panic unless the evaluation is `Denied` and the
    /// **top-level summary** denial reason contains `needle`.
    ///
    /// `needle` is matched against the single string on
    /// [`AccessEvaluation::Denied`] — a summary like
    /// `"All policies denied access"`, not the per-policy reasons
    /// inside the trace tree. For a multi-policy checker, asserting
    /// on a specific policy's reason needs [`Self::assert_trace_contains`]
    /// or [`Self::assert_not_applicable_by`].
    ///
    /// Substring match keeps tests resilient to minor reason-string
    /// rewording. For exact-match assertions, inspect
    /// [`Self::denied_reason`] directly.
    #[track_caller]
    pub fn assert_denied_with_reason_containing(&self, needle: &str) {
        match self {
            Self::Denied { reason, .. } => {
                assert!(
                    reason.contains(needle),
                    "expected summary denial reason to contain `{needle}`, got `{reason}`"
                );
            }
            Self::Granted { policy_type, .. } => {
                panic!(
                    "expected denial containing `{needle}`, but access was granted by `{policy_type}`"
                );
            }
            Self::Indeterminate { reason, .. } => {
                panic!(
                    "expected denial containing `{needle}`, but the evaluation was \
                     indeterminate: {reason}"
                );
            }
        }
    }

    /// Test helper: panic unless the evaluation is `Denied` and some
    /// `NotApplicable` leaf in the trace tree was produced by a policy whose
    /// name matches `expected`.
    ///
    /// Symmetric with [`Self::assert_granted_by`] but walks the trace
    /// rather than checking the top-level decision, because an ordinary final
    /// denial has no single denying policy: every policy in the checker declined
    /// to grant. Use this to assert that policy `expected` actually fired and
    /// was not applicable. Use [`Self::assert_forbidden_by`] for active vetoes.
    ///
    /// ```rust
    /// # use gatehouse::*;
    /// # tokio_test::block_on(async {
    /// # struct Domain;
    /// # impl PolicyDomain for Domain {
    /// #     type Subject = ();
    /// #     type Action = ();
    /// #     type Resource = ();
    /// #     type Context = ();
    /// # }
    /// # let mut checker = PermissionChecker::<Domain>::new();
    /// # checker.add_policy(
    /// #     PolicyBuilder::<Domain>::new("StaffOnly")
    /// #         .subjects(|_: &()| false)
    /// #         .build(),
    /// # );
    /// # let session = EvaluationSession::empty();
    /// # let evaluation = checker.bind(&session, &(), &(), &()).check(&()).await;
    /// evaluation.assert_not_applicable_by("StaffOnly");
    /// # });
    /// ```
    #[track_caller]
    pub fn assert_not_applicable_by(&self, expected: &str) {
        match self {
            Self::Granted { policy_type, .. } => {
                panic!(
                    "expected not-applicable by policy `{expected}`, but access was granted by `{policy_type}`"
                );
            }
            Self::Indeterminate { reason, .. } => {
                panic!(
                    "expected not-applicable by policy `{expected}`, but the evaluation was \
                     indeterminate: {reason}"
                );
            }
            Self::Denied { trace, .. } => {
                let Some(root) = trace.root() else {
                    panic!("expected not-applicable by `{expected}`, but the trace is empty");
                };
                if !leaf_not_applicable_matches(root, expected) {
                    panic!(
                        "expected a not-applicable leaf for policy `{expected}` in the trace; \
                         got:\n{}",
                        trace.format()
                    );
                }
            }
        }
    }

    /// Test helper: panic unless the evaluation is `Denied` *because of a
    /// forbid* by the policy named `expected`.
    ///
    /// Stronger than [`Self::assert_not_applicable_by`]: this asserts the denial
    /// was a deny-overrides veto attributed to `expected` (via
    /// [`Self::forbidden_by`]), not merely that `expected` appears as a
    /// not-applicable leaf somewhere in the trace.
    ///
    /// ```rust
    /// # use gatehouse::*;
    /// # tokio_test::block_on(async {
    /// # struct Domain;
    /// # impl PolicyDomain for Domain {
    /// #     type Subject = ();
    /// #     type Action = ();
    /// #     type Resource = ();
    /// #     type Context = ();
    /// # }
    /// # let mut checker = PermissionChecker::<Domain>::new();
    /// # checker.add_policy(PolicyBuilder::<Domain>::new("AllowAll").allow_all());
    /// # checker.add_veto(
    /// #     PolicyBuilder::<Domain>::new("GlobalFreeze")
    /// #         .forbid_all(),
    /// # );
    /// # let session = EvaluationSession::empty();
    /// # let evaluation = checker.bind(&session, &(), &(), &()).check(&()).await;
    /// evaluation.assert_forbidden_by("GlobalFreeze");
    /// # });
    /// ```
    #[track_caller]
    pub fn assert_forbidden_by(&self, expected: &str) {
        match self {
            Self::Granted { policy_type, .. } => {
                panic!(
                    "expected forbid by policy `{expected}`, but access was granted by `{policy_type}`"
                );
            }
            Self::Indeterminate { reason, .. } => {
                panic!(
                    "expected forbid by policy `{expected}`, but the evaluation was \
                     indeterminate: {reason}"
                );
            }
            Self::Denied { .. } => match self.forbidden_by() {
                Some(actual) => assert_eq!(
                    actual, expected,
                    "expected forbid by policy `{expected}`, but the forbid came from `{actual}`"
                ),
                None => panic!(
                    "expected forbid by policy `{expected}`, but the denial was not a forbid; \
                     got:\n{}",
                    self.display_trace()
                ),
            },
        }
    }

    /// Test helper: panic unless `needle` appears anywhere in the
    /// formatted evaluation trace.
    ///
    /// Substring match against the string produced by
    /// [`Self::display_trace`], which includes every per-policy
    /// reason (granted and denied) the checker actually evaluated.
    /// Use this when the assertion is "some policy in the trace
    /// produced this specific reason" — the per-policy reasons live
    /// in the trace, not on the top-level summary that
    /// [`Self::assert_denied_with_reason_containing`] inspects.
    #[track_caller]
    pub fn assert_trace_contains(&self, needle: &str) {
        let rendered = self.display_trace();
        assert!(
            rendered.contains(needle),
            "expected evaluation trace to contain `{needle}`; got:\n{rendered}"
        );
    }

    /// Converts the evaluation into a `Result`, mapping denial and indeterminate
    /// into the same reason-only error callback. Prefer [`Self::into_result`]
    /// when callers need to distinguish those outcomes.
    ///
    /// `error_fn` receives the denial reason string and should return your
    /// application's error type.
    ///
    /// Note that this uses the summary denial reason stored on
    /// [`AccessEvaluation::Denied`], not the individual child policy reasons from the
    /// trace tree. If you need the per-policy reasons, inspect [`EvalTrace`] first.
    ///
    /// ```rust
    /// # use gatehouse::*;
    /// # #[derive(Debug, Clone)]
    /// # struct User;
    /// # #[derive(Debug, Clone)]
    /// # struct Resource;
    /// # #[derive(Debug, Clone)]
    /// # struct Action;
    /// # #[derive(Debug, Clone)]
    /// # struct Ctx;
    /// # struct Domain;
    /// # impl PolicyDomain for Domain {
    /// #     type Subject = User;
    /// #     type Action = Action;
    /// #     type Resource = Resource;
    /// #     type Context = Ctx;
    /// # }
    /// # tokio_test::block_on(async {
    /// let checker = PermissionChecker::<Domain>::new();
    /// let session = EvaluationSession::empty();
    /// let result = checker.bind(&session, &User, &Action, &Ctx).check(&Resource).await;
    ///
    /// // Map a denial into a standard error:
    /// let outcome: Result<(), String> = result.to_result(|reason| reason.to_string());
    /// assert!(outcome.is_err());
    /// # });
    /// ```
    pub fn to_result<E>(&self, error_fn: impl FnOnce(&str) -> E) -> Result<(), E> {
        match self {
            Self::Granted { .. } => Ok(()),
            // Indeterminate is fail-closed: it maps to an error like a
            // denial. Callers that want to surface it differently (e.g.
            // as a 5xx) should branch on `is_indeterminate()` first.
            Self::Denied { reason, .. } | Self::Indeterminate { reason, .. } => {
                Err(error_fn(reason))
            }
        }
    }

    /// Converts a decision to a typed error, retaining the reason and complete audit trace.
    ///
    /// Unlike [`Self::to_result`], this distinguishes a definite denial from an
    /// inability to evaluate authorization. Map [`AccessError::Denied`] to a
    /// forbidden response and [`AccessError::Indeterminate`] to an appropriate
    /// service error in application code.
    ///
    /// ```
    /// use gatehouse::*;
    /// # struct Unit;
    /// # impl PolicyDomain for Unit {
    /// #     type Subject = ();
    /// #     type Action = ();
    /// #     type Resource = ();
    /// #     type Context = ();
    /// # }
    /// struct BackendDown;
    ///
    /// #[async_trait::async_trait]
    /// impl Policy<Unit> for BackendDown {
    ///     async fn evaluate(&self, _ctx: &EvalCtx<'_, Unit>) -> GrantResult {
    ///         GrantResult::indeterminate("BackendDown", "relationship backend unavailable")
    ///     }
    ///     fn policy_type(&self) -> std::borrow::Cow<'static, str> {
    ///         "BackendDown".into()
    ///     }
    /// }
    ///
    /// # tokio_test::block_on(async {
    /// let mut checker = PermissionChecker::<Unit>::new();
    /// checker.add_policy(BackendDown);
    /// let session = EvaluationSession::empty();
    /// let evaluation = checker.bind(&session, &(), &(), &()).check(&()).await;
    /// let status = match evaluation.into_result() {
    ///     Ok(()) => 200,
    ///     Err(AccessError::Denied { .. }) => 403,
    ///     Err(_) => 503,
    /// };
    /// assert_eq!(status, 503);
    /// # });
    /// ```
    pub fn into_result(self) -> Result<(), AccessError> {
        match self {
            Self::Granted { .. } => Ok(()),
            Self::Denied { reason, trace } => Err(AccessError::Denied { reason, trace }),
            Self::Indeterminate { reason, trace } => {
                Err(AccessError::Indeterminate { reason, trace })
            }
        }
    }

    /// Returns a human-readable string containing both the decision headline
    /// and the full evaluation trace tree.
    ///
    /// Useful for logging or debugging. The output includes the `Display`
    /// representation (e.g. `[GRANTED] by AdminPolicy - User is admin`)
    /// followed by the indented trace from [`EvalTrace::format`].
    pub fn display_trace(&self) -> String {
        // If there's an actual tree to show, add it. Otherwise, fallback.
        let trace_str = self.trace().format();
        if trace_str == "No evaluation trace available" {
            format!("{}\n(No evaluation trace available)", self)
        } else {
            format!("{}\nEvaluation Trace:\n{}", self, trace_str)
        }
    }
}

/// A concise line about the final decision.
impl fmt::Display for AccessEvaluation {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Granted {
                policy_type,
                reason,
                trace: _,
            } => {
                // Headline
                match reason {
                    Some(r) => write!(f, "[GRANTED] by {} - {}", policy_type, r),
                    None => write!(f, "[GRANTED] by {}", policy_type),
                }
            }
            Self::Denied { reason, trace: _ } => {
                write!(f, "[Denied] - {}", reason)
            }
            Self::Indeterminate { reason, trace: _ } => {
                write!(f, "[INDETERMINATE] - {}", reason)
            }
        }
    }
}

/// A tree of [`PolicyEvalResult`] nodes capturing every policy decision made
/// during an access evaluation.
///
/// Returned as part of [`AccessEvaluation`]. Use [`EvalTrace::format`] to render
/// a human-readable tree, useful for debugging and audit logging.
///
/// The tree records policy *decisions*. The *inputs* that informed a decision —
/// the facts a fact-backed policy consulted — are attached to the individual
/// [`PolicyEvalResult`] nodes as [`FactProvenance`] and rendered inline by
/// [`EvalTrace::format`]. Operational fact-load telemetry (latency, batch
/// fan-out, cache hits) is a separate concern surfaced through `tracing` spans
/// (`gatehouse.fact_load`), not through this tree.
///
/// # Example
///
/// ```rust
/// # use gatehouse::*;
/// // An empty trace produces a fallback message:
/// let empty = EvalTrace::new();
/// assert_eq!(empty.format(), "No evaluation trace available");
///
/// // A trace built from a policy result renders a decision tree:
/// let trace = EvalTrace::with_root(PolicyEvalResult::granted(
///     "AdminPolicy",
///     Some("User is admin".into()),
/// ));
/// assert!(trace.format().contains("AdminPolicy GRANTED"));
/// ```
#[derive(Debug, Clone, Default)]
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
pub struct EvalTrace {
    root: Option<PolicyEvalResult>,
}

impl EvalTrace {
    /// Creates an empty trace with no evaluation results.
    pub fn new() -> Self {
        Self { root: None }
    }

    /// Creates a trace with the given [`PolicyEvalResult`] as the root node.
    pub fn with_root(result: PolicyEvalResult) -> Self {
        Self { root: Some(result) }
    }

    /// Sets (or replaces) the root node of the evaluation tree.
    pub fn set_root(&mut self, result: PolicyEvalResult) {
        self.root = Some(result);
    }

    /// Returns a reference to the root [`PolicyEvalResult`], if present.
    pub fn root(&self) -> Option<&PolicyEvalResult> {
        self.root.as_ref()
    }

    /// Returns a formatted, indented representation of the evaluation tree.
    ///
    /// Each node shows a `✔` or `✘` prefix, the policy name, and the reason.
    /// Combined nodes indent their children for readability.
    pub fn format(&self) -> String {
        match &self.root {
            Some(root) => root.format(0),
            None => "No evaluation trace available".to_string(),
        }
    }
}

impl PolicyEvalResult {
    /// Builds a granted leaf result with no fact provenance.
    ///
    /// Prefer this over constructing [`PolicyEvalResult::Granted`] directly; use
    /// [`Self::granted_with_facts`] when the decision was informed by facts.
    ///
    /// `policy_type` accepts `&'static str` (zero-allocation, the common
    /// case), `String`, or any [`Cow<'static, str>`] convertible value.
    pub fn granted(policy_type: impl Into<Cow<'static, str>>, reason: Option<String>) -> Self {
        Self::Granted {
            policy_type: policy_type.into(),
            reason,
            provenance: Vec::new(),
        }
    }

    /// Builds a not-applicable leaf result with no fact provenance.
    ///
    /// Prefer this over constructing [`PolicyEvalResult::NotApplicable`] directly; use
    /// [`Self::not_applicable_with_facts`] when the decision was informed by facts.
    pub fn not_applicable(
        policy_type: impl Into<Cow<'static, str>>,
        reason: impl Into<String>,
    ) -> Self {
        Self::NotApplicable {
            policy_type: policy_type.into(),
            reason: reason.into(),
            provenance: Vec::new(),
        }
    }

    /// Builds a forbidden audit leaf with no fact provenance.
    ///
    /// This is an audit representation, not a veto result accepted by the
    /// checker. Custom veto policies return [`crate::VetoResult`] through
    /// [`crate::EvalCtx::forbid`] or [`crate::VetoResult::forbid`].
    pub fn forbidden(policy_type: impl Into<Cow<'static, str>>, reason: impl Into<String>) -> Self {
        Self::Forbidden {
            policy_type: policy_type.into(),
            reason: reason.into(),
            provenance: Vec::new(),
        }
    }

    /// Builds a granted leaf result carrying the facts that informed it.
    pub fn granted_with_facts(
        policy_type: impl Into<Cow<'static, str>>,
        reason: Option<String>,
        provenance: Vec<FactProvenance>,
    ) -> Self {
        Self::Granted {
            policy_type: policy_type.into(),
            reason,
            provenance,
        }
    }

    /// Builds an abstention with explicit facts, or an indeterminate result if
    /// any of those facts failed to load. The reason and facts are preserved.
    pub fn not_applicable_with_facts(
        policy_type: impl Into<Cow<'static, str>>,
        reason: impl Into<String>,
        provenance: Vec<FactProvenance>,
    ) -> Self {
        crate::policy::attach_recorded(Self::not_applicable(policy_type, reason), provenance)
    }

    /// Builds a forbidden leaf result carrying the facts that informed it.
    pub fn forbidden_with_facts(
        policy_type: impl Into<Cow<'static, str>>,
        reason: impl Into<String>,
        provenance: Vec<FactProvenance>,
    ) -> Self {
        Self::Forbidden {
            policy_type: policy_type.into(),
            reason: reason.into(),
            provenance,
        }
    }

    /// Builds an indeterminate leaf result with no fact provenance.
    ///
    /// Use this when the policy could not be evaluated because an input it
    /// needed was unavailable and the failure is explained by `reason`
    /// alone. Prefer [`Self::indeterminate_with_facts`] (or
    /// [`crate::EvalCtx::indeterminate`] inside policy bodies) when the
    /// failed fact loads are known, so callers can classify the failure via
    /// [`FactProvenance::error_kind`].
    pub fn indeterminate(
        policy_type: impl Into<Cow<'static, str>>,
        reason: impl Into<String>,
    ) -> Self {
        Self::Indeterminate {
            policy_type: policy_type.into(),
            reason: reason.into(),
            provenance: Vec::new(),
        }
    }

    /// Builds an indeterminate leaf result carrying the facts that could not
    /// be loaded (and any that were).
    pub fn indeterminate_with_facts(
        policy_type: impl Into<Cow<'static, str>>,
        reason: impl Into<String>,
        provenance: Vec<FactProvenance>,
    ) -> Self {
        Self::Indeterminate {
            policy_type: policy_type.into(),
            reason: reason.into(),
            provenance,
        }
    }

    /// Returns the decision carried by this node.
    ///
    /// Leaves map 1:1 onto their variant; [`PolicyEvalResult::Combined`]
    /// Returns the name of this audit-tree node.
    pub fn policy_type(&self) -> &str {
        match self {
            Self::Granted { policy_type, .. }
            | Self::NotApplicable { policy_type, .. }
            | Self::Forbidden { policy_type, .. }
            | Self::Indeterminate { policy_type, .. }
            | Self::Combined { policy_type, .. } => policy_type,
        }
    }

    /// returns its stored aggregate decision without walking children.
    pub fn decision(&self) -> Decision {
        match self {
            Self::Granted { .. } => Decision::Grant,
            Self::NotApplicable { .. } => Decision::NotApplicable,
            Self::Forbidden { .. } => Decision::Forbid,
            Self::Indeterminate { .. } => Decision::Indeterminate,
            Self::Combined { decision, .. } => *decision,
        }
    }

    /// Returns whether this evaluation resulted in access being granted
    pub fn is_granted(&self) -> bool {
        self.decision() == Decision::Grant
    }

    /// Whether this node's aggregate decision is a veto.
    ///
    /// Audit descendants can contain inactive vetoes (for example one child
    /// of an all-of veto whose other child passed). Only the node's decision
    /// carries authority.
    pub fn is_forbidden(&self) -> bool {
        self.decision() == Decision::Forbid
    }

    /// Walks the nodes that carried a definite `decision`, outermost first,
    /// skipping checker roots.
    ///
    /// OR, delegation, and checker-root nodes pass a decision up from one
    /// child, so the walk continues into the first child with that decision.
    /// Any other aggregate (AND, NOT, all-of veto) reached its decision as a
    /// whole and ends the walk: naming one of its children would credit a
    /// guard with an outcome that every child was needed for. The walk is
    /// empty when this node's decision differs.
    fn decisive_nodes(&self, decision: Decision) -> impl Iterator<Item = &Self> + '_ {
        std::iter::successors(
            (self.decision() == decision).then_some(self),
            move |node| match node {
                Self::Combined {
                    operation: CombineOp::Or | CombineOp::Delegate | CombineOp::DenyOverrides,
                    children,
                    ..
                } => children.iter().find(|child| child.decision() == decision),
                _ => None,
            },
        )
        .filter(|node| {
            !matches!(
                node,
                Self::Combined {
                    operation: CombineOp::DenyOverrides,
                    ..
                }
            )
        })
    }

    /// The grant spine: see [`Self::decisive_nodes`].
    pub(crate) fn grant_nodes(&self) -> impl Iterator<Item = &Self> + '_ {
        self.decisive_nodes(Decision::Grant)
    }

    /// The veto spine: see [`Self::decisive_nodes`].
    pub(crate) fn forbid_nodes(&self) -> impl Iterator<Item = &Self> + '_ {
        self.decisive_nodes(Decision::Forbid)
    }

    /// Names the node that decided a veto, with its reason when it is a leaf.
    pub(crate) fn forbidden_leaf(&self) -> Option<(&str, Option<&str>)> {
        self.forbid_nodes()
            .last()
            .map(|node| (node.policy_type(), node.reason_str()))
    }

    /// Attributes uncertainty along the active indeterminate spine.
    ///
    /// Resolved subtrees are skipped. An aggregate's own recorded failures
    /// are attributed to that aggregate. Every indeterminate aggregate the
    /// crate produces either contains an indeterminate leaf or carries a
    /// failed fact in its own provenance, so this search always names a
    /// policy for a crate-built tree.
    pub(crate) fn indeterminate_leaf(&self) -> Option<(&str, &str)> {
        const FACT_FAILURE_REASON: &str = "A consulted fact could not be loaded";
        match self {
            Self::Indeterminate {
                policy_type,
                reason,
                ..
            } => Some((policy_type.as_ref(), reason.as_str())),
            Self::Combined {
                policy_type,
                children,
                provenance,
                decision: Decision::Indeterminate,
                ..
            } => children
                .iter()
                .find_map(Self::indeterminate_leaf)
                .or_else(|| {
                    provenance
                        .iter()
                        .any(|fact| fact.outcome == FactOutcome::Error)
                        .then(|| (policy_type.as_ref(), FACT_FAILURE_REASON))
                }),
            Self::Combined { .. }
            | Self::Granted { .. }
            | Self::NotApplicable { .. }
            | Self::Forbidden { .. } => None,
        }
    }

    /// Returns the reason string if available
    pub fn reason(&self) -> Option<String> {
        self.reason_str().map(str::to_owned)
    }

    /// Returns the reason without cloning, if available.
    ///
    /// Borrowing analogue of [`Self::reason`] for callers that only need
    /// to inspect or render the reason.
    pub fn reason_str(&self) -> Option<&str> {
        match self {
            Self::Granted { reason, .. } => reason.as_deref(),
            Self::NotApplicable { reason, .. }
            | Self::Forbidden { reason, .. }
            | Self::Indeterminate { reason, .. } => Some(reason),
            Self::Combined { .. } => None,
        }
    }

    /// Returns the facts the policy consulted to reach this decision.
    ///
    /// Aggregate nodes contain their own facts; child facts remain on their children.
    pub fn provenance(&self) -> &[FactProvenance] {
        match self {
            Self::Granted { provenance, .. }
            | Self::NotApplicable { provenance, .. }
            | Self::Forbidden { provenance, .. }
            | Self::Indeterminate { provenance, .. }
            | Self::Combined { provenance, .. } => provenance,
        }
    }

    /// Formats the evaluation tree with indentation for readability
    pub fn format(&self, indent: usize) -> String {
        let indent_str = " ".repeat(indent);

        match self {
            Self::Granted {
                policy_type,
                reason,
                provenance,
            } => {
                let reason_text = reason
                    .as_ref()
                    .map_or("".to_string(), |r| format!(": {}", r));
                let headline = format!("{}✔ {} GRANTED{}", indent_str, policy_type, reason_text);
                Self::append_provenance(headline, &indent_str, provenance)
            }
            Self::NotApplicable {
                policy_type,
                reason,
                provenance,
            } => {
                let headline =
                    format!("{}✘ {} NOT_APPLICABLE: {}", indent_str, policy_type, reason);
                Self::append_provenance(headline, &indent_str, provenance)
            }
            Self::Forbidden {
                policy_type,
                reason,
                provenance,
            } => {
                let headline = format!("{}⛔ {} FORBIDDEN: {}", indent_str, policy_type, reason);
                Self::append_provenance(headline, &indent_str, provenance)
            }
            Self::Indeterminate {
                policy_type,
                reason,
                provenance,
            } => {
                let headline = format!("{}⚠ {} INDETERMINATE: {}", indent_str, policy_type, reason);
                Self::append_provenance(headline, &indent_str, provenance)
            }
            Self::Combined {
                policy_type,
                operation,
                children,
                decision,
                provenance,
            } => {
                let decision_char = match decision {
                    Decision::Grant => "✔",
                    Decision::NotApplicable => "✘",
                    Decision::Forbid => "⛔",
                    Decision::Indeterminate => "⚠",
                };
                let mut result = format!(
                    "{}{} {} ({})",
                    indent_str, decision_char, policy_type, operation
                );

                result = Self::append_provenance(result, &indent_str, provenance);
                for child in children {
                    result.push_str(&format!("\n{}", child.format(indent + 2)));
                }
                result
            }
        }
    }

    /// Appends one indented `↳ fact …` line per consulted fact under a leaf node.
    fn append_provenance(
        headline: String,
        indent_str: &str,
        provenance: &[FactProvenance],
    ) -> String {
        let mut result = headline;
        for fact in provenance {
            result.push_str(&format!("\n{indent_str}  ↳ {fact}"));
        }
        result
    }
}

impl fmt::Display for PolicyEvalResult {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let tree = self.format(0);
        write!(f, "{}", tree)
    }
}