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
use crate::{
    EvaluationSession, FactKey, FactLoadError, FactLoadResult, FactOutcome, FactProvenance,
    GrantResult, PolicyEvalResult, PolicyResult, SecurityRuleMetadata, VetoResult,
};
use async_trait::async_trait;
use std::borrow::Cow;
use std::sync::{Arc, Mutex};

/// Names the four Rust types that make up one authorization domain.
///
/// A domain is usually one resource family in an application: documents,
/// invoices, projects, packages. The marker type keeps policy APIs anchored to
/// a business domain instead of repeating `<Subject, Action, Resource, Context>`
/// on every checker, policy, and builder.
pub trait PolicyDomain: Send + Sync + 'static {
    /// Entity requesting access.
    type Subject: Send + Sync;
    /// Operation being attempted.
    type Action: Send + Sync;
    /// Target resource or scope resource.
    type Resource: Send + Sync;
    /// Request-scoped evaluation inputs.
    type Context: Send + Sync;
}

/// A borrowed resource passed to batch policy evaluators.
///
/// Values are borrowed from caller-owned batch items, so policy implementations
/// can evaluate a batch without forcing resources to be cloned.
pub struct PolicyBatchItem<'a, D: PolicyDomain> {
    /// The target resource for this item.
    pub resource: &'a D::Resource,
}

/// Merges context-recorded fact provenance into a result node.
///
/// Recorded entries precede any explicitly attached provenance (they were
/// loaded before the result was constructed). When the recorded entries
/// contain a [`FactOutcome::Error`] and the result is `NotApplicable`, the
/// leaf is upgraded to `Indeterminate`: the policy consulted an input that
/// was unavailable, so "did not grant" cannot be distinguished from "could
/// not decide" — the context witnessed the failure and reports it
/// structurally. Grants and forbids are decisive and are never rewritten.
/// Aggregate nodes follow the same rule and retain their own recorded facts.
pub(crate) fn attach_recorded(
    result: PolicyEvalResult,
    mut recorded: Vec<FactProvenance>,
) -> PolicyEvalResult {
    if recorded.is_empty() {
        return result;
    }
    let recorded_error = recorded
        .iter()
        .any(|fact| fact.outcome == FactOutcome::Error);
    match result {
        PolicyEvalResult::Granted {
            policy_type,
            reason,
            provenance,
        } => {
            recorded.extend(provenance);
            PolicyEvalResult::Granted {
                policy_type,
                reason,
                provenance: recorded,
            }
        }
        PolicyEvalResult::NotApplicable {
            policy_type,
            reason,
            provenance,
        } => {
            recorded.extend(provenance);
            if recorded_error {
                PolicyEvalResult::Indeterminate {
                    policy_type,
                    reason,
                    provenance: recorded,
                }
            } else {
                PolicyEvalResult::NotApplicable {
                    policy_type,
                    reason,
                    provenance: recorded,
                }
            }
        }
        PolicyEvalResult::Forbidden {
            policy_type,
            reason,
            provenance,
        } => {
            recorded.extend(provenance);
            PolicyEvalResult::Forbidden {
                policy_type,
                reason,
                provenance: recorded,
            }
        }
        PolicyEvalResult::Indeterminate {
            policy_type,
            reason,
            provenance,
        } => {
            recorded.extend(provenance);
            PolicyEvalResult::Indeterminate {
                policy_type,
                reason,
                provenance: recorded,
            }
        }
        PolicyEvalResult::Combined {
            policy_type,
            operation,
            children,
            decision,
            provenance,
        } => {
            recorded.extend(provenance);
            PolicyEvalResult::Combined {
                policy_type,
                operation,
                children,
                decision: if recorded_error && decision == crate::Decision::NotApplicable {
                    crate::Decision::Indeterminate
                } else {
                    decision
                },
                provenance: recorded,
            }
        }
    }
}

fn provenance_for<K: FactKey>(key: &K, result: &FactLoadResult<K::Value>) -> FactProvenance {
    FactProvenance::from_load_result(K::NAME, key.render(), result)
}

/// Keeps the context's fail-closed recording contract even if a future or
/// custom session implementation violates `get_many`'s length guarantee.
fn normalize_fact_result_count<K: FactKey>(
    results: Vec<FactLoadResult<K::Value>>,
    expected: usize,
) -> Vec<FactLoadResult<K::Value>> {
    if results.len() == expected {
        return results;
    }

    let actual = results.len();
    (0..expected)
        .map(|_| {
            FactLoadResult::Error(FactLoadError::SourceContractViolation {
                fact_name: K::NAME,
                expected,
                actual,
            })
        })
        .collect()
}

/// Per-item policy evaluation context.
///
/// Constructed by [`crate::PermissionChecker`] (or by [`Self::new`] in tests
/// and custom combinators). Fact loads should go through [`Self::fact`] /
/// [`Self::facts`], which record [`FactProvenance`] as a side effect; the
/// result helpers ([`Self::grant`], [`Self::not_applicable`],
/// [`Self::forbid`], [`Self::indeterminate`], and the `*_with_facts`
/// variants) attach everything recorded so far, so provenance is correct by
/// construction rather than opt-in.
pub struct EvalCtx<'a, D: PolicyDomain> {
    /// Request-scoped fact session. Private: load facts through
    /// [`Self::fact`] / [`Self::facts`], or reach the raw session via
    /// [`Self::session`] when recording must be bypassed.
    session: &'a EvaluationSession,
    /// Entity requesting access.
    pub subject: &'a D::Subject,
    /// Action being performed.
    pub action: &'a D::Action,
    /// Target resource.
    pub resource: &'a D::Resource,
    /// Additional per-request evaluation context.
    ///
    /// Carries request-scoped inputs that are not properties of the subject or
    /// resource: current time, MFA freshness, network zone, tenant-level
    /// overrides. Relationship data belongs behind a [`crate::FactSource`] and
    /// loads through [`EvaluationSession`].
    pub context: &'a D::Context,
    /// The current policy's [`Policy::policy_type`], captured by the checker
    /// before dispatch and used by [`Self::grant`],
    /// [`Self::not_applicable`], and [`Self::forbid`].
    pub policy_type: Cow<'static, str>,
    /// Facts consulted through this context and not yet attached to a
    /// result. A `std::sync::Mutex` (never held across an `await`) keeps the
    /// context `Sync` for `&self` use inside async policy bodies. Result
    /// helpers take this uncontended lock even on the fact-free path, while
    /// the empty `Vec` itself performs no heap allocation.
    recorded: Mutex<Vec<FactProvenance>>,
}

impl<'a, D: PolicyDomain> EvalCtx<'a, D> {
    /// Creates an evaluation context.
    ///
    /// [`crate::PermissionChecker`] builds contexts internally; this
    /// constructor exists for policy unit tests and custom combinators. A
    /// caller that invokes [`Policy::evaluate`] directly should pass the
    /// returned result through [`Self::finish`] afterwards so facts recorded
    /// by the policy but not attached by a result helper are not lost.
    #[inline]
    pub fn new(
        session: &'a EvaluationSession,
        subject: &'a D::Subject,
        action: &'a D::Action,
        resource: &'a D::Resource,
        context: &'a D::Context,
        policy_type: impl Into<Cow<'static, str>>,
    ) -> Self {
        Self {
            session,
            subject,
            action,
            resource,
            context,
            policy_type: policy_type.into(),
            recorded: Mutex::new(Vec::new()),
        }
    }

    /// Returns the raw request-scoped fact session.
    ///
    /// **Escape hatch**: loads made directly on the session are invisible to
    /// provenance recording — they will not appear in the evaluation trace,
    /// and a failed load reported through [`Self::not_applicable`] will not
    /// be upgraded to an indeterminate result. Prefer [`Self::fact`] /
    /// [`Self::facts`]. In particular, returning `NotApplicable` after an
    /// invisible failed load can be inverted to a grant by [`crate::NotPolicy`]
    /// because neither the result nor its provenance reports the failure.
    pub fn session(&self) -> &'a EvaluationSession {
        self.session
    }

    /// Loads one fact through the session and records its provenance.
    ///
    /// The recorded entry is attached to the result built by this context's
    /// result helpers (or merged by [`Self::finish`] when the policy builds
    /// its result by hand).
    pub async fn fact<K>(&self, key: K) -> FactLoadResult<K::Value>
    where
        K: FactKey,
    {
        let rendered = key.render();
        let result = self.session.get(key).await;
        self.record(FactProvenance::from_load_result(K::NAME, rendered, &result));
        result
    }

    /// Loads many facts through the session and records one provenance entry
    /// per key, in input order.
    pub async fn facts<K>(&self, keys: &[K]) -> Vec<FactLoadResult<K::Value>>
    where
        K: FactKey,
    {
        let results =
            normalize_fact_result_count::<K>(self.session.get_many(keys).await, keys.len());
        let mut recorded = self.recorded.lock().expect("recorded facts poisoned");
        for (key, result) in keys.iter().zip(&results) {
            recorded.push(provenance_for(key, result));
        }
        results
    }

    /// Records an already-built provenance entry against this context.
    ///
    /// For facts loaded outside [`Self::fact`] / [`Self::facts`] (for
    /// example through a caller-owned loader) that should still appear on
    /// the policy's result.
    pub fn record(&self, provenance: FactProvenance) {
        self.recorded
            .lock()
            .expect("recorded facts poisoned")
            .push(provenance);
    }

    fn take_recorded(&self) -> Vec<FactProvenance> {
        std::mem::take(&mut *self.recorded.lock().expect("recorded facts poisoned"))
    }

    /// Merges any facts recorded on this context but not yet attached into
    /// `result`, consuming the context.
    ///
    /// [`crate::PermissionChecker`] and the built-in combinators call this
    /// after every [`Policy::evaluate`], so a policy that loads facts through
    /// [`Self::fact`] and then builds a [`GrantResult`] or [`VetoResult`] directly still
    /// produces full provenance — and a hand-built `NotApplicable` after a
    /// recorded load failure is upgraded to `Indeterminate` (see
    /// [`Self::not_applicable`]). Call it yourself when driving
    /// [`Policy::evaluate`] directly. Aggregate nodes retain their own facts
    /// and follow the same decision rules as leaves.
    #[inline]
    pub fn finish<R: PolicyResult>(self, result: R) -> R {
        let recorded = self.recorded.into_inner().expect("recorded facts poisoned");
        if recorded.is_empty() {
            return result;
        }
        result.attach_recorded(recorded)
    }

    /// Builds a granted result tagged with `ctx.policy_type`, attaching all
    /// facts recorded on this context.
    pub fn grant(&self, reason: impl Into<String>) -> GrantResult {
        GrantResult(attach_recorded(
            PolicyEvalResult::granted(self.policy_type.clone(), Some(reason.into())),
            self.take_recorded(),
        ))
    }

    /// Builds a not-applicable result tagged with `ctx.policy_type`,
    /// attaching all facts recorded on this context.
    ///
    /// If a fact recorded through [`Self::fact`] / [`Self::facts`] failed to
    /// load ([`FactOutcome::Error`]), the result is **upgraded to
    /// [`PolicyEvalResult::Indeterminate`]**: the policy consulted an input
    /// that was unavailable, so it cannot claim an ordinary non-match. This
    /// closes the silent gap where `ctx.not_applicable(...)` after a failed
    /// load looked identical to a genuine non-match. Use
    /// [`Self::session`] to load without recording when this behavior is
    /// truly not wanted.
    pub fn not_applicable(&self, reason: impl Into<String>) -> GrantResult {
        GrantResult(attach_recorded(
            PolicyEvalResult::not_applicable(self.policy_type.clone(), reason),
            self.take_recorded(),
        ))
    }

    /// Builds a forbidden result tagged with `ctx.policy_type`, attaching
    /// all facts recorded on this context.
    ///
    /// Returns a veto result, which cannot be returned by a grant policy.
    pub fn forbid(&self, reason: impl Into<String>) -> VetoResult {
        VetoResult(attach_recorded(
            PolicyEvalResult::forbidden(self.policy_type.clone(), reason),
            self.take_recorded(),
        ))
    }

    /// Builds an indeterminate result tagged with `ctx.policy_type`,
    /// attaching all facts recorded on this context.
    ///
    /// Use this when the policy cannot decide because an input it needed was
    /// unavailable — typically after [`Self::fact`] returned
    /// [`FactLoadResult::Error`]. Fail-closed: never treated as a grant, and
    /// surfaced as [`crate::AccessEvaluation::Indeterminate`] when decisive.
    pub fn indeterminate(&self, reason: impl Into<String>) -> GrantResult {
        GrantResult(attach_recorded(
            PolicyEvalResult::indeterminate(self.policy_type.clone(), reason),
            self.take_recorded(),
        ))
    }

    /// Builds a passing veto result and attaches recorded facts.
    pub fn pass(&self, reason: impl Into<String>) -> VetoResult {
        VetoResult(attach_recorded(
            PolicyEvalResult::not_applicable(self.policy_type.clone(), reason),
            self.take_recorded(),
        ))
    }

    /// Builds an unresolved veto result and attaches recorded facts.
    pub fn veto_indeterminate(&self, reason: impl Into<String>) -> VetoResult {
        VetoResult(attach_recorded(
            PolicyEvalResult::indeterminate(self.policy_type.clone(), reason),
            self.take_recorded(),
        ))
    }

    /// [`Self::grant`] with extra explicit provenance appended after the
    /// recorded entries.
    pub fn grant_with_facts(
        &self,
        reason: impl Into<String>,
        provenance: Vec<FactProvenance>,
    ) -> GrantResult {
        GrantResult(attach_recorded(
            PolicyEvalResult::granted_with_facts(
                self.policy_type.clone(),
                Some(reason.into()),
                provenance,
            ),
            self.take_recorded(),
        ))
    }

    /// [`Self::not_applicable`] with extra explicit provenance appended
    /// after the recorded entries.
    ///
    /// Either recorded or explicit failed facts upgrade the abstention to
    /// `Indeterminate`, preserving its reason and evidence.
    pub fn not_applicable_with_facts(
        &self,
        reason: impl Into<String>,
        provenance: Vec<FactProvenance>,
    ) -> GrantResult {
        GrantResult(attach_recorded(
            PolicyEvalResult::not_applicable_with_facts(
                self.policy_type.clone(),
                reason,
                provenance,
            ),
            self.take_recorded(),
        ))
    }

    /// [`Self::forbid`] with extra explicit provenance appended after the
    /// recorded entries.
    pub fn forbid_with_facts(
        &self,
        reason: impl Into<String>,
        provenance: Vec<FactProvenance>,
    ) -> VetoResult {
        VetoResult(attach_recorded(
            PolicyEvalResult::forbidden_with_facts(self.policy_type.clone(), reason, provenance),
            self.take_recorded(),
        ))
    }

    /// [`Self::indeterminate`] with extra explicit provenance appended after
    /// the recorded entries.
    pub fn indeterminate_with_facts(
        &self,
        reason: impl Into<String>,
        provenance: Vec<FactProvenance>,
    ) -> GrantResult {
        GrantResult(attach_recorded(
            PolicyEvalResult::indeterminate_with_facts(
                self.policy_type.clone(),
                reason,
                provenance,
            ),
            self.take_recorded(),
        ))
    }
}

/// Batch policy evaluation context.
///
/// A batch holds one subject, one action, and one request context evaluated
/// against many resources. Fact loads should go through [`Self::facts_by`]
/// (one key per item) or [`Self::fact`] (one key shared by every item), which
/// record [`FactProvenance`] against the originating items; the caller —
/// [`crate::PermissionChecker`] or a combinator — merges the recorded entries
/// into the per-item results via [`Self::finish`].
pub struct BatchEvalCtx<'a, D: PolicyDomain> {
    /// Request-scoped fact session. Private: load facts through
    /// [`Self::facts_by`] / [`Self::fact`], or reach the raw session via
    /// [`Self::session`] when recording must be bypassed.
    session: &'a EvaluationSession,
    /// Entity requesting access.
    pub subject: &'a D::Subject,
    /// Action being performed, shared across every item in the batch.
    pub action: &'a D::Action,
    /// Request-scoped context, shared across every item in the batch.
    pub context: &'a D::Context,
    /// Borrowed resources.
    pub items: &'a [PolicyBatchItem<'a, D>],
    /// The current policy's [`Policy::policy_type`].
    pub policy_type: Cow<'static, str>,
    /// Per-item recorded provenance, lazily sized to `items.len()` on first
    /// use so the fact-free path performs no per-item heap allocation.
    recorded: Mutex<Vec<Vec<FactProvenance>>>,
}

impl<'a, D: PolicyDomain> BatchEvalCtx<'a, D> {
    /// Creates a batch evaluation context.
    ///
    /// [`crate::PermissionChecker`] builds contexts internally; this
    /// constructor exists for policy unit tests and custom combinators. A
    /// caller that invokes [`Policy::evaluate_batch`] directly should pass
    /// the returned results through [`Self::finish`] afterwards so recorded
    /// facts reach the per-item results.
    #[inline]
    pub fn new(
        session: &'a EvaluationSession,
        subject: &'a D::Subject,
        action: &'a D::Action,
        context: &'a D::Context,
        items: &'a [PolicyBatchItem<'a, D>],
        policy_type: impl Into<Cow<'static, str>>,
    ) -> Self {
        Self {
            session,
            subject,
            action,
            context,
            items,
            policy_type: policy_type.into(),
            recorded: Mutex::new(Vec::new()),
        }
    }

    /// Returns the raw request-scoped fact session.
    ///
    /// **Escape hatch**: loads made directly on the session are invisible to
    /// provenance recording. Prefer [`Self::facts_by`] / [`Self::fact`]. In
    /// particular, an invisible failed load followed by `NotApplicable` can
    /// be inverted to a grant by [`crate::NotPolicy`] because no failure is
    /// present in the result or provenance.
    pub fn session(&self) -> &'a EvaluationSession {
        self.session
    }

    /// Builds one fact key per item, loads them through the session in a
    /// single deduplicated call, records provenance against the originating
    /// item, and returns results aligned with [`Self::items`].
    pub async fn facts_by<K, F>(&self, key_of: F) -> Vec<FactLoadResult<K::Value>>
    where
        K: FactKey,
        F: Fn(&D::Resource) -> K,
    {
        let keys = self
            .items
            .iter()
            .map(|item| key_of(item.resource))
            .collect::<Vec<_>>();
        let results =
            normalize_fact_result_count::<K>(self.session.get_many(&keys).await, keys.len());
        let mut recorded = self.recorded_slots();
        for (index, (key, result)) in keys.iter().zip(&results).enumerate() {
            recorded[index].push(provenance_for(key, result));
        }
        results
    }

    /// Loads one fact shared by every item in the batch (for example a
    /// per-subject lookup) and records its provenance against each item.
    pub async fn fact<K>(&self, key: K) -> FactLoadResult<K::Value>
    where
        K: FactKey,
    {
        let rendered = key.render();
        let result = self.session.get(key).await;
        let provenance = FactProvenance::from_load_result(K::NAME, rendered, &result);
        let mut recorded = self.recorded_slots();
        for slot in recorded.iter_mut() {
            slot.push(provenance.clone());
        }
        result
    }

    fn recorded_slots(&self) -> std::sync::MutexGuard<'_, Vec<Vec<FactProvenance>>> {
        let mut recorded = self.recorded.lock().expect("recorded facts poisoned");
        if recorded.is_empty() {
            recorded.resize_with(self.items.len(), Vec::new);
        }
        recorded
    }

    /// Merges the facts recorded per item into the matching results,
    /// consuming the context.
    ///
    /// Applies the same rules as [`EvalCtx::finish`] per item, including the
    /// `NotApplicable` → `Indeterminate` upgrade on recorded load failures.
    /// A `results` vector whose length does not match [`Self::items`] is
    /// returned unchanged (the caller's wrong-length handling applies).
    #[inline]
    pub fn finish<R: PolicyResult>(self, results: Vec<R>) -> Vec<R> {
        let recorded = self.recorded.into_inner().expect("recorded facts poisoned");
        if recorded.is_empty() || results.len() != recorded.len() {
            return results;
        }
        results
            .into_iter()
            .zip(recorded)
            .map(|(result, recorded)| result.attach_recorded(recorded))
            .collect()
    }
}

/// A grant policy for one [`PolicyDomain`].
///
/// Returns [`GrantResult`], which can grant, abstain, or be indeterminate.
/// Implement [`crate::VetoPolicy`] for rules that can veto; grant policies
/// cannot return veto authority. Register grants with
/// [`crate::PermissionChecker::add_policy`].
#[async_trait]
pub trait Policy<D: PolicyDomain>: Send + Sync {
    /// Evaluates whether access should be granted.
    async fn evaluate(&self, ctx: &EvalCtx<'_, D>) -> GrantResult;

    /// Evaluates access for a batch of resources.
    ///
    /// The default implementation preserves single-item semantics by evaluating
    /// each item sequentially. Policies with set-oriented backends can override
    /// this method to reduce round trips while returning one result per input
    /// item in the same order.
    async fn evaluate_batch<'item>(&self, ctx: &BatchEvalCtx<'item, D>) -> Vec<GrantResult> {
        let mut results = Vec::with_capacity(ctx.items.len());
        for item in ctx.items {
            let item_ctx = EvalCtx::new(
                ctx.session(),
                ctx.subject,
                ctx.action,
                item.resource,
                ctx.context,
                ctx.policy_type.clone(),
            );
            let result = self.evaluate(&item_ctx).await;
            results.push(item_ctx.finish(result));
        }
        results
    }

    /// Policy name for debugging, trace trees, and telemetry fallbacks.
    fn policy_type(&self) -> Cow<'static, str>;

    /// Metadata describing the security rule that backs this policy.
    fn security_rule(&self) -> SecurityRuleMetadata {
        SecurityRuleMetadata::default()
    }
}

#[async_trait]
impl<D> Policy<D> for Box<dyn Policy<D>>
where
    D: PolicyDomain,
{
    async fn evaluate(&self, ctx: &EvalCtx<'_, D>) -> GrantResult {
        (**self).evaluate(ctx).await
    }

    async fn evaluate_batch<'item>(&self, ctx: &BatchEvalCtx<'item, D>) -> Vec<GrantResult> {
        (**self).evaluate_batch(ctx).await
    }

    fn policy_type(&self) -> Cow<'static, str> {
        (**self).policy_type()
    }

    fn security_rule(&self) -> SecurityRuleMetadata {
        (**self).security_rule()
    }
}

#[async_trait]
impl<D> Policy<D> for Arc<dyn Policy<D>>
where
    D: PolicyDomain,
{
    async fn evaluate(&self, ctx: &EvalCtx<'_, D>) -> GrantResult {
        (**self).evaluate(ctx).await
    }

    async fn evaluate_batch<'item>(&self, ctx: &BatchEvalCtx<'item, D>) -> Vec<GrantResult> {
        (**self).evaluate_batch(ctx).await
    }

    fn policy_type(&self) -> Cow<'static, str> {
        (**self).policy_type()
    }

    fn security_rule(&self) -> SecurityRuleMetadata {
        (**self).security_rule()
    }
}