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
# Migrating from 0.5.1 to 0.6.0

Fix the compile errors first; the compiler finds every one. Then work
through the changes that compile unchanged but alter authorization results,
audit output or telemetry. Rust 1.82 remains the minimum supported compiler.
The historical 0.4 → 0.5 guide follows at the end and describes that older
API only.

Three changes compile unchanged and alter results. Read these before you
deploy:

- [Preserve outages at application boundaries]#preserve-outages-at-application-boundaries:
  an outage is now `Indeterminate`, and an existing `_ =>` arm on
  `AccessEvaluation` receives it.
- [Record consulted facts]#record-consulted-facts: a policy that reads the
  raw session with `ctx.session()` still fails open during an outage.
- [PolicyBuilder predicates accumulate]#policybuilder-predicates-accumulate:
  a repeated builder setter now narrows the policy, so a veto fires less
  often.

[Mechanical search hints](#mechanical-search-hints) lists searches that find
the call sites for each change.

Upgrading from a 0.6.0 prerelease? 0.6.0 has the same API as 0.6.0-alpha.3.
From alpha.2, read [Decisions name the policy that decided them](#decisions-name-the-policy-that-decided-them),
[Decisions are sealed](#decisions-are-sealed) and
[Backend error text stays out of audit output](#backend-error-text-stays-out-of-audit-output).
From alpha.1, also read
[PolicyBuilder predicates accumulate](#policybuilder-predicates-accumulate)
and [Explicit lossy collection names](#explicit-lossy-collection-names).

## Separate grants from vetoes

`Policy<D>::evaluate` now returns `GrantResult`, and `evaluate_batch` returns
`Vec<GrantResult>`. These results can grant, abstain, or be indeterminate;
they cannot veto. Existing grant policies generally need only to change their
return type and replace `PolicyEvalResult` constructors with `GrantResult`
constructors. Context helpers (`ctx.grant`, `ctx.not_applicable`, and
`ctx.indeterminate`) already return the correct type.

Veto rules implement `VetoPolicy<D>` and return `VetoResult`. Use
`ctx.forbid`, `ctx.pass`, or `ctx.veto_indeterminate`. Register them with
`checker.add_veto(...)`. A passing veto never grants access. `Effect`,
`Policy::effect`, `add_forbid_policy`, and `PolicyBuilder::forbid` are removed.
For predicates, replace `.forbid().build()` with `.build_veto()`:

```rust
use gatehouse::*;

struct Accounts;
impl PolicyDomain for Accounts {
    type Subject = bool; // whether the account is suspended
    type Action = ();
    type Resource = ();
    type Context = ();
}

let mut checker = PermissionChecker::<Accounts>::new();
checker.add_policy(PolicyBuilder::<Accounts>::new("Member").allow_all());
checker.add_veto(
    PolicyBuilder::<Accounts>::new("Suspended")
        .subjects(|suspended| *suspended)
        .build_veto(),
);
```

For a custom rule that previously both granted and vetoed, split it into
separate grant and veto policies. Register both directly, or put both in a
child checker and register it once with `add_delegate` to keep the two halves
atomic. This is the replacement for an `AllowOrForbid` policy. Share backend
inputs through a request-scoped fact session in either case. The type checker
now rejects a grant policy returning a veto, rather than relying on a correctly
declared effect.

## Composition and delegation

`PolicyExt::and`, `or`, and `not` accept grant policies only. For a local
exclusion, use `grant.and(blocked.not())`, where `blocked` is an ordinary
predicate grant. A veto cannot be embedded in this expression.

Use `AllOfVeto` / `VetoPolicyExt::all_of` when every child must veto to block,
and `AnyOfVeto` / `VetoPolicyExt::any_of` when any child veto should block.
A definite pass settles an all-of veto; a definite veto settles an any-of
veto. Otherwise uncertainty remains indeterminate. There is no veto negation.
Dynamic policy combinators reject empty collections.

Custom grant result composition uses `GrantResult::all` / `any`. Empty
result collections abstain. Their aggregate decisions are computed by the
constructors; compose veto policies with `AllOfVeto` / `AnyOfVeto`. `PolicyEvalResult`
remains the inspectable audit tree, including `Combined { decision,
provenance, children, .. }`; policies cannot return it or convert an arbitrary
raw tree into an authority-bearing result. Use `result.trace()` to inspect
and `PolicyResult::into_trace()` to consume a typed result into its audit tree.

`DelegatingPolicy` no longer implements `Policy<D>`. Register it with
**`checker.add_delegate(delegate)`**, not `add_policy`. It also cannot be passed
to `and`, `or`, `not`, or `AndPolicy::try_new`. There is no direct replacement
for a delegate inside a grant combinator: compose the grant rules inside the
child checker and register the child with `add_delegate`, keeping its vetoes
separate. Review the intended scope of those vetoes, since a delegated veto
blocks every parent grant path.

That one registration installs both capabilities atomically. Child veto
uncertainty blocks parent grants; a child grant failure does not block an
independent parent grant after the child's vetoes pass. Each child capability
phase runs at most once for each parent evaluation; delegation retains batch
execution and nested evidence.

## PolicyBuilder predicates accumulate

`subjects`, `actions`, `resources`, `context`, and `when` now append to their
axis instead of replacing it. Every predicate on every axis must return `true`
for the builder's condition to hold. Builders that set each axis at most once
retain their decisions for deterministic predicates, but scalar evaluation now
runs context predicates before resource predicates. Callers relying on evaluation
order must account for that change. Predicates must return deterministic results
for the supplied inputs: subject, action, and context predicates run at most once
per nonempty batch, and no predicates run for an empty batch.

A builder that set one axis twice changes meaning without any source change:

```rust,ignore
// The same source, before and after.
let active_admin = PolicyBuilder::<Documents>::new("ActiveAdmin")
    .subjects(|user| user.active)
    .subjects(|user| user.is_admin)
    .build();

// Before: the second call replaced the first, so only `is_admin` was checked
// and an inactive admin was granted access.
// After: both predicates must hold, and an inactive admin no longer matches.
```

To preserve the previous behavior, retain only the final predicate on each
repeated axis. To deliberately broaden the new conjunction, compose separate
policies with `PolicyExt::or`. This is an intentional policy change: the example
below also admits active non-admins, whereas the old repeated-setter policy
required `is_admin`:

```rust,ignore
let active = PolicyBuilder::<Documents>::new("Active")
    .subjects(|user| user.active)
    .build();
let admin = PolicyBuilder::<Documents>::new("Admin")
    .subjects(|user| user.is_admin)
    .build();

checker.add_policy(active.or(admin));
```

There is deliberately no replace or clear operation. Adding a predicate can
only narrow a grant.

`build_veto` shares the same match condition, so a second predicate narrows
*when the veto fires*, not what it blocks once fired. **Upgrading an existing
repeated-setter veto can therefore increase the set of requests ultimately
permitted.** A veto that must fire on
either condition is two vetoes combined with `VetoPolicyExt::any_of`, or
`AnyOfVeto::try_new` for a dynamic list:

```rust,ignore
// Fires only when the account is suspended AND the document is on legal hold.
let narrow = PolicyBuilder::<Documents>::new("Blocked")
    .subjects(|user| user.suspended)
    .resources(|document| document.legal_hold)
    .build_veto();

// Fires when either condition holds.
let suspended = PolicyBuilder::<Documents>::new("Suspended")
    .subjects(|user| user.suspended)
    .build_veto();
let legal_hold = PolicyBuilder::<Documents>::new("LegalHold")
    .resources(|document| document.legal_hold)
    .build_veto();

checker.add_veto(suspended.any_of(legal_hold));
```

An empty builder no longer builds anything. `build` and `build_veto` exist
only after at least one predicate, so a policy that applies to every request
names itself:

```rust,ignore
// Before
let allow_all = PolicyBuilder::<Documents>::new("AllowAll").build();
let freeze = PolicyBuilder::<Documents>::new("Freeze").build_veto();

// After
let allow_all = PolicyBuilder::<Documents>::new("AllowAll").allow_all();
let freeze = PolicyBuilder::<Documents>::new("Freeze").forbid_all();
```

`allow_all` grants every request; `forbid_all` forbids every request. Result
reasons are unchanged. Calling `build()` or `build_veto()` without a predicate
is now a compile error, so the compiler locates every site for you.

Helpers that supply predicates must return `PolicyBuilder<Documents, Conditional>`
instead of the default `PolicyBuilder<Documents>` (which means `Unconditional`).
A decorator accepting either state must also return `Conditional` after adding a
predicate:

```rust,ignore
use gatehouse::{BuilderState, Conditional, PolicyBuilder};

fn active_users() -> PolicyBuilder<Documents, Conditional> {
    PolicyBuilder::<Documents>::new("Active").subjects(|user| user.active)
}

fn require_admin<S: BuilderState>(
    builder: PolicyBuilder<Documents, S>,
) -> PolicyBuilder<Documents, Conditional> {
    builder.subjects(|user| user.is_admin)
}

let active_admin = require_admin(active_users()).build();
```

Checklist for this section:

1. Find builders that set the same axis twice. Retain only the final predicate
   to preserve the old behavior, or explicitly choose the new conjunction or
   separate alternatives with `or` (grants) or `any_of` (vetoes).
2. Replace empty `build()` with `allow_all()` and empty `build_veto()` with
   `forbid_all()`.
3. Re-run authorization tests covering subjects that satisfy only part of a
   rule, such as an inactive admin or a suspended owner.

Searches for this section:

```shell
rg "\\.(subjects|actions|resources|context|when)\\("
rg "new(_owned|_static)?\\([^)]*\\)\\s*\\.\\s*build(_veto)?\\(\\)"
```

The first lists every predicate call, so a chain that repeats one axis is easy
to spot; the second finds the empty builders that must become `allow_all` /
`forbid_all`.

## Preserve outages at application boundaries

`AccessEvaluation` has three outcomes: `Granted`, `Denied`, and
`Indeterminate`. A definite veto wins over uncertainty. An unresolved veto
blocks grants. A failed grant policy can be superseded by an independent
grant; without a grant, its failure makes the evaluation indeterminate.

Replace reason-only `to_result(...)` conversion or blanket 403 responses with
`into_result()` and classify `AccessError`:

```rust
use gatehouse::{AccessError, AccessEvaluation};

fn status(evaluation: AccessEvaluation) -> u16 {
    match evaluation.into_result() {
        Ok(()) => 200,
        Err(AccessError::Denied { .. }) => 403,
        Err(_) => 503,
    }
}
```

`AccessEvaluation` was already `#[non_exhaustive]`, so a `match` outside
the crate has a wildcard arm, and that arm now silently receives
`Indeterminate`. A `_ =>` that denies reports an outage as a policy decision,
with a 403 where a 503 belongs. Handle the outcome explicitly, or use
`into_result()` as above:

```rust
use gatehouse::AccessEvaluation;

fn status(evaluation: &AccessEvaluation) -> u16 {
    match evaluation {
        AccessEvaluation::Granted { .. } => 200,
        AccessEvaluation::Denied { .. } => 403,
        AccessEvaluation::Indeterminate { .. } => 503,
        _ => 503,
    }
}
```

`AccessError` retains the full trace and exposes `fact_load_errors()` for
structured classification. Applications can implement `From<AccessError>`
for their own error type and then use `check(...).await.into_result()?`.
Inspect `FactProvenance::error_kind` to distinguish backend failures,
unregistered sources, contract violations, and cancelled loaders. Keep
trace details in internal diagnostics rather than HTTP response bodies.

For complete lists, migrate:

| Previous call | Strict replacement |
| --- | --- |
| `filter(resources).await` | `try_filter(resources).await?` |
| `filter_by(rows, projection).await` | `try_filter_by(rows, projection).await?` |
| `lookup_page(...).await?` | `try_lookup_page(...).await?` |

Strict filtering excludes definite denials but returns `FilterError<Item>`
if any final decision is indeterminate. The error owns **all** original items
and evaluations in input order; `indeterminate()` selects unresolved items.
A grant that supersedes an irrelevant failure succeeds normally. No partial
list is returned as success.

`try_lookup_page` returns `LookupAuthorizedError<LookupErr, HydrateErr,
Resource>`. Its `Evaluation` variant retains hydrated resources and their
decisions; source, hydration, and contract errors remain distinct variants.
An authorization failure returns no next cursor: retry the same input cursor
with a fresh session after recovery. Previously returned pages cannot be
retracted, so an endpoint requiring an atomic multi-page response must collect
all pages before sending it.

A `LookupSource` that returns more IDs than the requested `limit` fails
with `LookupAuthorizedError::LookupPageTooLarge { limit, actual }` before
hydration or authorization; 0.5.1 authorized the whole page. Make the source
honour `limit`. The error's third type parameter, `Resource`, defaults to
`()`, so a signature that names `LookupAuthorizedError<L, H>` still compiles;
a `match` on it needs arms for the `Evaluation` and `LookupPageTooLarge`
variants, or a wildcard.

`AccessEvaluation`, `GrantResult`, `VetoResult` and awaited
`BoundEvaluator::evaluate` results are `#[must_use]`, and the old list names
and `denied_due_to_fact_load_error()` are deprecated, so a build that denies
warnings fails until each is addressed. `denied_due_to_fact_load_error()`
detects any error in the trace, which may be irrelevant to the final decision;
use `is_indeterminate()` or `into_result()`, and `fact_load_errors()` for
diagnostics. It is planned for removal in 0.7.

## Explicit lossy collection names

`filter`, `filter_by`, and `lookup_page` are deprecated forwarding aliases;
their behavior is unchanged, so they still omit indeterminate items along
with denials. Use the `try_` methods above to surface outages. If dropping
indeterminate items is intentional, migrate to `filter_lossy`,
`filter_by_lossy`, and `lookup_page_lossy`. Lossy lookup still returns
lookup, hydration, and adapter-contract errors.

## Record consulted facts

Use `ctx.fact(key)` / `ctx.facts(keys)` instead of raw session loads. Batch
policies use `ctx.facts_by(key_of)` or `ctx.fact(shared_key)`. These APIs load
through the session and record successful, missing, and failed facts. The
checker and built-in combinators attach the recorded evidence automatically.

```rust
use async_trait::async_trait;
use gatehouse::*;
use std::borrow::Cow;

#[derive(Debug, Clone, Hash, PartialEq, Eq)]
struct Membership(u64);
impl FactKey for Membership {
    type Value = bool;
    const NAME: &'static str = "membership";
}
struct Documents;
impl PolicyDomain for Documents {
    type Subject = u64;
    type Action = ();
    type Resource = ();
    type Context = ();
}
struct Member;
#[async_trait]
impl Policy<Documents> for Member {
    async fn evaluate(&self, ctx: &EvalCtx<'_, Documents>) -> GrantResult {
        match ctx.fact(Membership(*ctx.subject)).await {
            FactLoadResult::Found(true) => ctx.grant("member"),
            _ => ctx.not_applicable("membership not established"),
        }
    }
    fn policy_type(&self) -> Cow<'static, str> { "Member".into() }
}
```

**`ctx.session` is not a safe rename.** The raw session is now read with
`ctx.session()`, and the mechanical rename compiles. Only facts loaded through
`ctx.fact`, `ctx.facts`, `ctx.facts_by` and `RebacPolicy` turn a failed load
into `Indeterminate`; a policy that reads the session directly keeps the
0.5.1 behaviour. There, a failed load looks like an abstention, so
`member.and(blocked.not())` grants when the `blocked` lookup fails, and a
veto whose data source failed lets the grant through. Load through the
context, or map `FactLoadResult::Error` yourself:

```rust,ignore
// Compiles after the rename, and still fails open.
match ctx.session().get(Blocked(*ctx.subject)).await {
    FactLoadResult::Found(true) => ctx.grant("blocked"),
    _ => ctx.not_applicable("not blocked"),
}

// Fails closed: the recorded failure makes the result Indeterminate.
match ctx.fact(Blocked(*ctx.subject)).await {
    FactLoadResult::Found(true) => ctx.grant("blocked"),
    _ => ctx.not_applicable("not blocked"),
}

// Also fails closed, when the load must stay on the session.
match ctx.session().get(Suspended(*ctx.subject)).await {
    FactLoadResult::Found(true) => ctx.forbid("suspended"),
    FactLoadResult::Found(false) | FactLoadResult::Missing => ctx.pass("active"),
    FactLoadResult::Error(_) => ctx.veto_indeterminate("suspension lookup failed"),
}
```

A recorded failure upgrades abstention or veto pass to `Indeterminate`.
This also applies to explicit `*_with_facts` constructors when the result's
own provenance contains `FactOutcome::Error`; the reason and facts are retained.
Decisive grants and vetoes retain their decisions even if an optional recorded
load failed. This rule is the same for leaf and aggregate results. `Combined`
now stores its own provenance; child evidence remains on child nodes. There
are no synthetic failure children and no shape-dependent loss of evidence.
Negation uses the resulting decision, not errors elsewhere in the audit tree:
`NOT(AND[indeterminate, definite-abstain])` grants because the conjunction is
definitely unsatisfied. An irrelevant descendant failure does not make that
settled aggregate uncertain again.

When invoking a policy directly, call `ctx.finish(result)` or
`batch_ctx.finish(results)`. Construct contexts with `EvalCtx::new` /
`BatchEvalCtx::new`; their recorders and session fields are private.
`ctx.session()` is an explicit non-recording escape hatch. Use
`ctx.record(FactProvenance::from_load_result(...))` for externally loaded facts.

Other source and behavior changes:

- `FactKey` requires `Debug` and has a default `render()` for audit keys.
  `RelationshipQuery` requires `Debug` on IDs and relations, plus `Display`
  on the relation. Override `render()` to control diagnostic key text.
- `FactProvenance` gains `error_kind`. Add `error_kind: None` to old struct
  literals, or prefer `from_load_result`. `new` produces unclassified evidence.
- `RebacPolicy` returns indeterminate for failed loads. `Missing` and
  `Found(false)` still abstain. The failure's `error_kind` and audit-safe detail stay in provenance.
- Wrong-length policy batches produce indeterminate results. Veto failures
  block grants; grant failures can be superseded by a later grant.
- `NotPolicy` preserves uncertainty, including explicit failed-load evidence
  on an abstaining result. Never disguise an unrecorded failure as abstention.
- `assert_denied()` no longer accepts indeterminate evaluations. Use
  `assert_indeterminate()` for outage tests.
- Serialized audit nodes gain `decision` and aggregate `provenance` fields;
  update consumers that previously expected `Combined.outcome`.

## Decisions name the policy that decided them

Grants and vetoes follow one rule. An `OrPolicy`, `AnyOfVeto`, or delegate
passes the decision up from its first deciding child, so
`granted_policy_type()`, `forbidden_by()`, `assert_granted_by`,
`assert_forbidden_by`, and the summary reason name that child. An
`AndPolicy`, `NotPolicy`, or `AllOfVeto` decides as a whole and is named
itself; 0.5.1 named the first child of an `AllOfVeto`.

A grant through `a.or(b)` used to report `OrPolicy` and now reports `a` or
`b`, with that policy's reason. This also changes the `Granted` display, the
serialized `policy_type`, and the evaluation span's `policy.type`. Update
assertions such as `assert_granted_by("OrPolicy")`, or ones naming a
delegate, to name the deciding child, and any dashboard that groups by
`policy.type`. Per-policy `gatehouse::security` events still name the
registered policy.

`grant_path()` and `forbidden_path()` return the chain from the registered
policy (for example a delegate or `OrPolicy`) down to the decider. Give a
combinator a stable name with `.named("...")`.

## Decisions are sealed

The variants of `AccessEvaluation` and `AccessError`, and the `FilterError`
and `LookupAuthorizedPage` structs, can be read and matched but not
constructed outside Gatehouse. Add `..` to struct patterns on the enum
variants, for example `AccessError::Denied { reason, .. }`. Tests that built
a decision by hand should obtain one from a `PermissionChecker` instead.

## Backend error text stays out of audit output

Backend errors, such as database errors, can quote row values. For an error
wrapped with `FactLoadError::backend(err)`, `FactProvenance::detail` is a
fixed placeholder (`backend error (message withheld from audit output)`) in
provenance, traces, logs and serialized output, and `RebacPolicy` reasons
name the failure class instead of quoting the error. To record a
description, use `FactLoadError::backend_with_message("safe text", err)`.
`err` stays available through `std::error::Error::source` for your own logs.

## Optional instrumentation

`tracing` is a default-enabled Cargo feature. In 0.5.1 it was always
compiled in, so a dependency declared with `default-features = false` now
loses its spans, security events and contract warnings unless it also
enables `tracing`. Decisions, the returned `EvalTrace`, and fact provenance
are unaffected and have the same semantics. `serde` is independent and can be
enabled without tracing.

Outages are reported differently from denials:

| Telemetry | 0.5.1 | 0.6.0 |
| --- | --- | --- |
| Evaluation span `outcome` | `denied` | `indeterminate` |
| Security event `event.outcome` | `failure` | `unknown` |
| Batch span `denied_count` | included outages | excludes outages |
| Batch span `indeterminate_count` | absent | outages |

`policy.effect` is `allow` or `deny`. Alerts and dashboards that count
denials or failures stop seeing outages; add a rule for the new values.

## Before you deploy

Run custom policy and batch tests, inject fact backend failures into single
and list endpoints, and check every wildcard match on `AccessEvaluation`.
Create a fresh session for retries and each reauthorization pass so cached
failures or stale permissions are not reused.

## Mechanical search hints

Each search lists call sites to review, with the action to take:

```shell
# Removed: use build_veto and add_veto (Separate grants from vetoes).
rg 'add_forbid_policy|\.forbid\(\)|Effect::|fn effect'

# Policies can no longer return it: return GrantResult or VetoResult.
rg 'PolicyEvalResult'

# Builders that repeat a setter, and empty builders (PolicyBuilder section).
rg '\.(subjects|actions|resources|context|when)\('
rg 'new(_owned|_static)?\([^)]*\)\s*\.\s*build(_veto)?\(\)'

# Raw session reads fail open: load with ctx.fact, ctx.facts or ctx.facts_by.
rg 'ctx\.session\b'

# Reason-only conversion merges outages and denials: use into_result().
rg '\bto_result\('

# Deprecated: use is_indeterminate() or into_result().
rg 'denied_due_to_fact_load_error'

# Deprecated, lossy: use try_filter, try_filter_by, try_lookup_page,
# or the _lossy name when dropping outages is intended.
rg '\.(filter|filter_by|lookup_page)\('

# Outage tests: assert_denied now fails on Indeterminate.
rg 'assert_denied'

# Wildcard arms now receive Indeterminate: add an explicit arm.
rg -U '(?s)AccessEvaluation::.{0,400}?_ =>' --glob '*.rs'

# Lookup errors: handle Evaluation and LookupPageTooLarge.
rg 'LookupAuthorizedError'

# tracing is now a default feature: re-enable it if you rely on telemetry.
rg 'gatehouse.*default-features\s*=\s*false' --glob 'Cargo.toml'

# Struct literals need error_kind: use FactProvenance::from_load_result.
rg 'FactProvenance \{'

# Message withheld from audit output: use backend_with_message if it is safe.
rg 'FactLoadError::backend\('

# Helpers that return a builder after adding a predicate.
rg 'PolicyBuilder<[^>]*>\s*\{'
```

---

# Historical: migrating from 0.4 to 0.5

This section describes the released 0.5 API. Its Effect declarations, raw policy
results, and mixed combinators are superseded by the 0.6 guide above.

Gatehouse 0.5 intentionally breaks the public API to make the authorization surface smaller and harder to misuse. The main changes are:

- policies are parameterized by one `PolicyDomain` instead of four repeated generics;
- every checker call goes through a session-bound evaluator;
- policy-level non-grants are now `NotApplicable`;
- explicit veto policies use `forbid` / `Effect::Forbid`;
- forbids propagate through combinators and delegation;
- built-in ABAC is removed in favor of `PolicyBuilder::when`.

If you are upgrading from 0.2 or 0.3, first read the release notes for 0.3 and 0.4 in `CHANGELOG.md`, then apply this guide.

## Migration checklist

1. Define one `PolicyDomain` marker per authorization domain.
2. Change `Policy<S, A, R, C>` impls to `Policy<Domain>`.
3. Change `EvalCtx<'_, S, A, R, C>` to `EvalCtx<'_, Domain>`.
4. Replace `ctx.deny(...)` with `ctx.not_applicable(...)`.
5. Replace `PolicyEvalResult::Denied` with `PolicyEvalResult::NotApplicable`.
6. Replace `PolicyBuilder::<S, A, R, C>` with `PolicyBuilder::<Domain>`.
7. Replace `checker.check(...)`, `evaluate_in_session(...)`, batch, filter, and lookup checker methods with `checker.bind(...).check(...)`, `.evaluate(...)`, `.try_filter(...)`, or `.try_lookup_page(...)`.
8. Build request sessions through `FactRegistry` for fact-backed policies.
9. Replace `AbacPolicy` with `PolicyBuilder::when` or a hand-written `Policy`.
10. Update direct `BatchEvalCtx` / `PolicyBatchItem` construction in tests.
11. Add wildcard arms to matches on public gatehouse enums; they are now `#[non_exhaustive]`.

## Policy domains

Before, the same four generic parameters appeared on every policy, builder, and checker:

```rust,ignore
type DocumentChecker = PermissionChecker<User, ReadAction, Document, RequestContext>;

impl Policy<User, ReadAction, Document, RequestContext> for OwnerPolicy {
    async fn evaluate(
        &self,
        ctx: &EvalCtx<'_, User, ReadAction, Document, RequestContext>,
    ) -> PolicyEvalResult {
        // ...
    }
}
```

Now define a domain marker once:

```rust,ignore
use gatehouse::PolicyDomain;

struct Documents;

impl PolicyDomain for Documents {
    type Subject = User;
    type Action = ReadAction;
    type Resource = Document;
    type Context = RequestContext;
}
```

Then use that domain everywhere:

```rust,ignore
type DocumentChecker = PermissionChecker<Documents>;

impl Policy<Documents> for OwnerPolicy {
    async fn evaluate(&self, ctx: &EvalCtx<'_, Documents>) -> PolicyEvalResult {
        // ...
    }
}
```

The associated types are always read in `Subject`, `Action`, `Resource`, `Context` order.

## Policy results

`PolicyEvalResult::Denied` used to mean "this policy did not grant". That was too easy to confuse with the final top-level `AccessEvaluation::Denied`.

Policy-level non-grants are now `PolicyEvalResult::NotApplicable`:

```rust,ignore
// Before
if ctx.subject.id == ctx.resource.owner_id {
    ctx.grant("owner")
} else {
    ctx.deny("not owner")
}

// After
if ctx.subject.id == ctx.resource.owner_id {
    ctx.grant("owner")
} else {
    ctx.not_applicable("not owner")
}
```

For direct constructors:

```rust,ignore
// Before
PolicyEvalResult::denied("OwnerPolicy", "not owner")

// After
PolicyEvalResult::not_applicable("OwnerPolicy", "not owner")
```

`AccessEvaluation::Denied` still exists. It is the final result returned by the checker when no policy grants or a forbid policy vetoes.

## Forbid policies

Explicit veto rules use `Effect::Forbid` and `PolicyEvalResult::Forbidden`. `PolicyBuilder` has a direct `.forbid()` helper:

```rust,ignore
let suspended_account = PolicyBuilder::<Documents>::new("SuspendedAccount")
    .when(|user, _action, _doc, _ctx| user.is_suspended)
    .forbid()
    .build();
```

A hand-written policy that can veto should return `ctx.forbid(...)` and declare its effect:

```rust,ignore
impl Policy<Documents> for LegalHold {
    async fn evaluate(&self, ctx: &EvalCtx<'_, Documents>) -> PolicyEvalResult {
        if ctx.resource.legal_hold {
            ctx.forbid("document is under legal hold")
        } else {
            ctx.not_applicable("no legal hold")
        }
    }

    fn effect(&self) -> Effect {
        Effect::Forbid
    }
}
```

Forbid-effect policies are evaluated before allow-only policies, so their result is not skipped by the grant short-circuit. If a hand-written policy can return `Forbidden` but does not declare `Effect::Forbid` or `Effect::AllowOrForbid`, the checker can only honor the veto if evaluation reaches that policy before a grant.

`Forbidden` now propagates through `AndPolicy`, `OrPolicy`, `NotPolicy`, and `DelegatingPolicy`. If you previously placed a forbid policy inside a combinator expecting it to behave like an ordinary non-grant, change that local guard into a normal grant-style predicate and wrap it with `not()`:

```rust,ignore
let muted = PolicyBuilder::<Threads>::new("Muted")
    .subjects(|member| member.muted)
    .build();

let collaborator_unless_muted = collaborator.and(muted.not());
```

Use `.forbid()` only when a match should actively veto every grant path in the composed decision.

`not()` cannot cancel an active veto. A policy like `admin.or(blocked.not())` still denies if `blocked` returns `Forbidden`; this is the intended absolute-veto behavior. Similarly, `grant.and(forbid_only)` can never grant because a forbid-only child never satisfies AND's "all children grant" rule. For a scoped "grant unless blocked" condition, make `blocked` a normal allow-style predicate and compose `grant.and(blocked.not())`.

## PolicyBuilder

`PolicyBuilder` is now domain-parameterized:

```rust,ignore
// Before
let owner = PolicyBuilder::<User, ReadAction, Document, RequestContext>::new("Owner")
    .when(|user, _action, doc, _ctx| user.id == doc.owner_id)
    .build();

// After
let owner = PolicyBuilder::<Documents>::new("Owner")
    .when(|user, _action, doc, _ctx| user.id == doc.owner_id)
    .build();
```

Use `.subjects`, `.actions`, `.resources`, and `.context` for single-axis predicates. Use `.when` when the predicate compares multiple inputs. The generated batch path evaluates subject, action, and context predicates once per batch and resource / cross-axis predicates per item.

`PolicyBuilder::new` accepts `impl Into<Cow<'static, str>>`: a `'static` literal (`new("Owner")`) is zero-allocation on the trace path; runtime names (`new(format!(...))`) remain owned. Existing `new("literal")` call sites pick up the zero-alloc path with no source change.

## Checker calls

The old API had several entry points:

```rust,ignore
checker.check(&user, &Read, &document, &request_context).await;

checker
    .evaluate_in_session(&session, &user, &Read, &document, &request_context)
    .await;

checker
    .filter_authorized_in_session_by_resource(
        &session,
        &user,
        &Read,
        documents,
        &request_context,
        |document| document,
    )
    .await;
```

The new API binds request-wide inputs once:

```rust,ignore
let session = EvaluationSession::empty();
let bound = checker.bind(&session, &user, &Read, &request_context);

let decision = bound.check(&document).await;
let decisions = bound.evaluate(documents.clone()).await;
let visible = bound.try_filter(documents).await?;
```

When the list item is a wider row than the authorization resource, use the extractor variants and keep returning the original rows:

```rust,ignore
let decisions = bound
    .evaluate_by(invoice_rows.clone(), |row| &row.authz_resource)
    .await;

let visible_rows = bound
    .try_filter_by(invoice_rows, |row| &row.authz_resource)
    .await?;
```

For fact-backed policies, create the session from a registry:

```rust,ignore
let registry = FactRegistry::builder()
    .with_arc::<RelationshipQuery<UserId, DocumentId, Relation>>(relationships)
    .build();

let session = registry.session();
let decision = checker
    .bind(&session, &user, &Read, &request_context)
    .check(&document)
    .await;
```

`EvaluationSession::empty()` and `EvaluationSession::shared_empty()` remain available for fact-free policy stacks, but every evaluation now receives a session explicitly. This removes the old "fact-backed checker accidentally used the no-session `check` path" footgun.

## Batch evaluation

`BoundEvaluator::evaluate` and `BoundEvaluator::try_filter` accept caller-owned resources. Items only need to borrow as `D::Resource`:

```rust,ignore
let results: Vec<(Document, AccessEvaluation)> = bound.evaluate(documents).await;
```

If you constructed `BatchEvalCtx` directly in tests or custom combinators, note the shape changed:

```rust,ignore
let items = docs
    .iter()
    .map(|resource| PolicyBatchItem::<Documents> { resource })
    .collect::<Vec<_>>();

let ctx = BatchEvalCtx {
    session: &session,
    subject: &user,
    action: &Read,
    context: &request_context,
    items: &items,
    policy_type: policy.policy_type(),
};
```

`PolicyBatchItem` no longer carries a per-item context. Batch evaluation is one subject, one action, one request context, and many resources. If you need different contexts, group the inputs and evaluate one bound batch per context.

## Long-lived streams

`EvaluationSession` is still scoped to one authorization pass. For SSE, WebSocket, and other long-lived streams, do not keep one fact-backed session for the stream lifetime.

If your product contract authorizes once at stream open, create a fresh session, compute the visible ID set with `try_filter` / `try_filter_by`, drop the session, and only emit frames for that set. If the stream must observe mid-stream permission revocation, run periodic reauthorization with a fresh `registry.session()` each tick and re-bind the checker for that pass.

## Lookup APIs

`LookupSource` is now domain-parameterized:

```rust,ignore
#[async_trait]
impl LookupSource<Documents> for DocumentLookup {
    type Id = DocumentId;
    type Error = LookupError;

    async fn lookup_page(
        &self,
        subject: &User,
        action: &ReadAction,
        context: &RequestContext,
        cursor: Option<&[u8]>,
        limit: NonZeroUsize,
    ) -> Result<LookupPage<DocumentId>, LookupError> {
        // ...
    }
}
```

Call lookup through the bound evaluator:

```rust,ignore
let page = checker
    .bind(&session, &user, &Read, &request_context)
    .try_lookup_page(&lookup, &hydrator, cursor.as_deref(), limit)
    .await?;
```

The lookup source still must enumerate a superset of every resource any policy could grant. Gatehouse only narrows and authorizes the hydrated subset; it does not discover grant paths the lookup source omitted.

## Built-in policy changes

### RbacPolicy

`RbacPolicy` now takes the domain as its first generic parameter:

```rust,ignore
let policy = RbacPolicy::<Documents, _, _>::new(required_roles, subject_roles);
```

Inference often fills the closure types once the policy is added to a `PermissionChecker<Documents>`.

### RebacPolicy

`RebacPolicy` also takes the domain:

```rust,ignore
let policy = RebacPolicy::<Documents, UserId, DocumentId, Relation>::new(
    |user| user.id,
    |document| document.id,
    Relation::Viewer,
);
```

Relationship facts are still loaded through `RelationshipQuery<UserId, DocumentId, Relation>` registered in the request session.

### DelegatingPolicy

`DelegatingPolicy` maps from one domain to another:

```rust,ignore
let delegate = DelegatingPolicy::<Comments, Documents>::new(
    "DocumentEditAllowsCommentModeration",
    document_checker,
    |comment_user| comment_user.clone(),
    |_action| DocumentAction::Edit,
    |_subject, _action, comment, _ctx| comment.document.clone(),
    |_subject, _action, ctx| ctx.document_context.clone(),
);
```

The context mapper runs once per bound batch. The resource mapper still runs per resource.

## AbacPolicy removal

`AbacPolicy` is removed. Use `PolicyBuilder::when` for synchronous attribute-style checks:

```rust,ignore
let owner = PolicyBuilder::<Documents>::new("Owner")
    .when(|user, _action, document, _ctx| user.id == document.owner_id)
    .build();
```

Use a hand-written `Policy<Domain>` when the rule needs async work, custom batching, custom telemetry metadata, or explicit forbid behavior.

## Tests and assertions

Tests that asserted policy-level denials should now assert not-applicability:

```rust,ignore
evaluation.assert_not_applicable_by("Owner");
```

Use `assert_forbidden_by` for active vetoes and `assert_denied` / `assert_denied_with_reason_containing` for final access denials.

## Public enum matching

Public gatehouse enums are now `#[non_exhaustive]`, including `AccessEvaluation`, `PolicyEvalResult`, `Effect`, `FactLoadResult`, `FactLoadError`, and lookup errors. Add wildcard arms and fail closed for unknown access decisions:

```rust,ignore
match evaluation {
    AccessEvaluation::Granted { .. } => Ok(()),
    AccessEvaluation::Denied { reason, .. } => Err(reason),
    _ => Err("unknown access decision".into()),
}
```

## Dependency changes

`uuid` moved out of normal dependencies; it is only used by examples, tests, and doctests. If your application used gatehouse's transitive `uuid`, add `uuid` to your own `Cargo.toml`.

The new optional `serde` feature derives `Serialize` for decision and trace types (`AccessEvaluation`, `EvalTrace`, `PolicyEvalResult`, `FactProvenance`, and related value enums) for audit logging pipelines.

## Mechanical search hints (0.4 to 0.5)

These searches catch most migration work:

```shell
rg "Policy<[^>]*,[^>]*,[^>]*,[^>]*"
rg "PolicyBuilder::<[^>]*,[^>]*,[^>]*,[^>]*"
rg "EvalCtx<'_, [^>]*,[^>]*"
rg "ctx\\.deny|PolicyEvalResult::Denied|PolicyEvalResult::denied"
rg "evaluate_in_session|filter_authorized|lookup_authorized|\\.check\\(&"
rg "AbacPolicy|Effect::Deny"
rg "AccessEvaluation::|PolicyEvalResult::|FactLoadResult::|LookupAuthorizedError::"
```