gatehouse 0.5.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
use crate::{
    BatchEvalCtx, CombineOp, Effect, EvalCtx, Policy, PolicyBatchItem, PolicyDomain,
    PolicyEvalResult,
};
use async_trait::async_trait;
use std::sync::Arc;

fn arc_policy<D, P>(policy: P) -> Arc<dyn Policy<D>>
where
    D: PolicyDomain,
    P: Policy<D> + 'static,
{
    Arc::new(policy)
}

fn ordered_policies<D>(policies: Vec<Arc<dyn Policy<D>>>) -> (Vec<Arc<dyn Policy<D>>>, usize)
where
    D: PolicyDomain,
{
    let mut veto_capable = Vec::new();
    let mut allow_only = Vec::new();
    for policy in policies {
        if policy.effect().can_forbid() {
            veto_capable.push(policy);
        } else {
            allow_only.push(policy);
        }
    }
    let veto_capable_count = veto_capable.len();
    let mut ordered = Vec::with_capacity(veto_capable_count + allow_only.len());
    ordered.extend(veto_capable);
    ordered.extend(allow_only);
    (ordered, veto_capable_count)
}

fn any_child_can_forbid<D>(policies: &[Arc<dyn Policy<D>>]) -> bool
where
    D: PolicyDomain,
{
    policies.iter().any(|policy| policy.effect().can_forbid())
}

/// Fluent combinator helpers for policies.
pub trait PolicyExt<D>: Policy<D> + Sized + 'static
where
    D: PolicyDomain,
{
    /// Requires this policy and `other` to grant.
    fn and<P>(self, other: P) -> AndPolicy<D>
    where
        P: Policy<D> + 'static,
    {
        AndPolicy::from_policies(vec![arc_policy::<D, _>(self), arc_policy::<D, _>(other)])
    }

    /// Grants when this policy or `other` grants.
    fn or<P>(self, other: P) -> OrPolicy<D>
    where
        P: Policy<D> + 'static,
    {
        OrPolicy::from_policies(vec![arc_policy::<D, _>(self), arc_policy::<D, _>(other)])
    }

    /// Inverts this policy.
    fn not(self) -> NotPolicy<D> {
        NotPolicy {
            policy: arc_policy::<D, _>(self),
        }
    }

    /// Boxes this policy as a trait object.
    fn boxed(self) -> Box<dyn Policy<D>> {
        Box::new(self)
    }
}

impl<D, P> PolicyExt<D> for P
where
    D: PolicyDomain,
    P: Policy<D> + Sized + 'static,
{
}

/// Combines multiple policies with logical AND semantics.
pub struct AndPolicy<D: PolicyDomain> {
    policies: Vec<Arc<dyn Policy<D>>>,
    veto_capable_count: usize,
}

/// Error returned when no policies are provided to a combinator policy.
#[derive(Debug, Copy, Clone)]
pub struct EmptyPoliciesError(pub &'static str);

impl std::fmt::Display for EmptyPoliciesError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str(self.0)
    }
}

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

impl<D: PolicyDomain> AndPolicy<D> {
    fn from_policies(policies: Vec<Arc<dyn Policy<D>>>) -> Self {
        let (policies, veto_capable_count) = ordered_policies(policies);
        Self {
            policies,
            veto_capable_count,
        }
    }

    /// Creates a new `AndPolicy` from a non-empty list of policies.
    pub fn try_new(policies: Vec<Arc<dyn Policy<D>>>) -> Result<Self, EmptyPoliciesError> {
        if policies.is_empty() {
            Err(EmptyPoliciesError(
                "AndPolicy must have at least one policy",
            ))
        } else {
            Ok(Self::from_policies(policies))
        }
    }
}

#[async_trait]
impl<D: PolicyDomain> Policy<D> for AndPolicy<D> {
    fn policy_type(&self) -> std::borrow::Cow<'static, str> {
        std::borrow::Cow::Borrowed("AndPolicy")
    }

    fn effect(&self) -> Effect {
        let can_grant = self
            .policies
            .iter()
            .all(|policy| policy.effect().can_grant());
        Effect::from_capabilities(can_grant, any_child_can_forbid(&self.policies))
    }

    async fn evaluate(&self, ctx: &EvalCtx<'_, D>) -> PolicyEvalResult {
        let mut children_results = Vec::with_capacity(self.policies.len());
        let mut veto_prefix_failed = false;

        for (policy_index, policy) in self.policies.iter().enumerate() {
            let inner_ctx = EvalCtx {
                session: ctx.session,
                subject: ctx.subject,
                action: ctx.action,
                resource: ctx.resource,
                context: ctx.context,
                policy_type: policy.policy_type(),
            };
            let result = policy.evaluate(&inner_ctx).await;
            let is_granted = result.is_granted();
            let is_forbidden = result.is_forbidden();
            children_results.push(result);

            if is_forbidden {
                return PolicyEvalResult::Combined {
                    policy_type: self.policy_type(),
                    operation: CombineOp::And,
                    children: children_results,
                    outcome: false,
                };
            }

            if policy_index < self.veto_capable_count {
                veto_prefix_failed |= !is_granted;
                if policy_index + 1 == self.veto_capable_count && veto_prefix_failed {
                    return PolicyEvalResult::Combined {
                        policy_type: self.policy_type(),
                        operation: CombineOp::And,
                        children: children_results,
                        outcome: false,
                    };
                }
            } else if !is_granted {
                return PolicyEvalResult::Combined {
                    policy_type: self.policy_type(),
                    operation: CombineOp::And,
                    children: children_results,
                    outcome: false,
                };
            }
        }

        PolicyEvalResult::Combined {
            policy_type: self.policy_type(),
            operation: CombineOp::And,
            children: children_results,
            outcome: true,
        }
    }

    async fn evaluate_batch<'item>(&self, ctx: &BatchEvalCtx<'item, D>) -> Vec<PolicyEvalResult> {
        let mut children_by_item = vec![Vec::new(); ctx.items.len()];
        let mut results = vec![None; ctx.items.len()];
        let mut pending = (0..ctx.items.len()).collect::<Vec<_>>();
        let mut veto_prefix_failed = vec![false; ctx.items.len()];

        for (policy_index, policy) in self.policies.iter().enumerate() {
            if pending.is_empty() {
                break;
            }

            let batch_items = pending
                .iter()
                .map(|&index| PolicyBatchItem {
                    resource: ctx.items[index].resource,
                })
                .collect::<Vec<_>>();
            let batch_ctx = BatchEvalCtx {
                session: ctx.session,
                subject: ctx.subject,
                action: ctx.action,
                context: ctx.context,
                items: &batch_items,
                policy_type: policy.policy_type(),
            };
            let child_results = policy.evaluate_batch(&batch_ctx).await;

            if child_results.len() != pending.len() {
                for index in pending.drain(..) {
                    children_by_item[index].push(PolicyEvalResult::not_applicable(
                        policy.policy_type(),
                        "Policy batch result count did not match input count",
                    ));
                    results[index] = Some(PolicyEvalResult::Combined {
                        policy_type: self.policy_type(),
                        operation: CombineOp::And,
                        children: std::mem::take(&mut children_by_item[index]),
                        outcome: false,
                    });
                }
                break;
            }

            let mut still_pending = Vec::new();
            for (index, child_result) in pending.into_iter().zip(child_results) {
                let is_granted = child_result.is_granted();
                let is_forbidden = child_result.is_forbidden();
                children_by_item[index].push(child_result);

                if is_forbidden {
                    results[index] = Some(PolicyEvalResult::Combined {
                        policy_type: self.policy_type(),
                        operation: CombineOp::And,
                        children: std::mem::take(&mut children_by_item[index]),
                        outcome: false,
                    });
                } else if policy_index < self.veto_capable_count {
                    veto_prefix_failed[index] |= !is_granted;
                    if policy_index + 1 == self.veto_capable_count && veto_prefix_failed[index] {
                        results[index] = Some(PolicyEvalResult::Combined {
                            policy_type: self.policy_type(),
                            operation: CombineOp::And,
                            children: std::mem::take(&mut children_by_item[index]),
                            outcome: false,
                        });
                    } else {
                        still_pending.push(index);
                    }
                } else if is_granted {
                    still_pending.push(index);
                } else {
                    results[index] = Some(PolicyEvalResult::Combined {
                        policy_type: self.policy_type(),
                        operation: CombineOp::And,
                        children: std::mem::take(&mut children_by_item[index]),
                        outcome: false,
                    });
                }
            }
            pending = still_pending;
        }

        for index in pending {
            results[index] = Some(PolicyEvalResult::Combined {
                policy_type: self.policy_type(),
                operation: CombineOp::And,
                children: std::mem::take(&mut children_by_item[index]),
                outcome: true,
            });
        }

        results
            .into_iter()
            .map(|result| {
                result.unwrap_or_else(|| {
                    PolicyEvalResult::not_applicable(
                        self.policy_type(),
                        "Batch item was not evaluated",
                    )
                })
            })
            .collect()
    }
}

/// Combines multiple policies with logical OR semantics.
pub struct OrPolicy<D: PolicyDomain> {
    policies: Vec<Arc<dyn Policy<D>>>,
    veto_capable_count: usize,
}

impl<D: PolicyDomain> OrPolicy<D> {
    fn from_policies(policies: Vec<Arc<dyn Policy<D>>>) -> Self {
        let (policies, veto_capable_count) = ordered_policies(policies);
        Self {
            policies,
            veto_capable_count,
        }
    }

    /// Creates a new `OrPolicy` from a non-empty list of policies.
    pub fn try_new(policies: Vec<Arc<dyn Policy<D>>>) -> Result<Self, EmptyPoliciesError> {
        if policies.is_empty() {
            Err(EmptyPoliciesError("OrPolicy must have at least one policy"))
        } else {
            Ok(Self::from_policies(policies))
        }
    }
}

#[async_trait]
impl<D: PolicyDomain> Policy<D> for OrPolicy<D> {
    fn policy_type(&self) -> std::borrow::Cow<'static, str> {
        std::borrow::Cow::Borrowed("OrPolicy")
    }

    fn effect(&self) -> Effect {
        let can_grant = self
            .policies
            .iter()
            .any(|policy| policy.effect().can_grant());
        Effect::from_capabilities(can_grant, any_child_can_forbid(&self.policies))
    }

    async fn evaluate(&self, ctx: &EvalCtx<'_, D>) -> PolicyEvalResult {
        let mut children_results = Vec::with_capacity(self.policies.len());
        let mut veto_prefix_granted = false;

        for (policy_index, policy) in self.policies.iter().enumerate() {
            let inner_ctx = EvalCtx {
                session: ctx.session,
                subject: ctx.subject,
                action: ctx.action,
                resource: ctx.resource,
                context: ctx.context,
                policy_type: policy.policy_type(),
            };
            let result = policy.evaluate(&inner_ctx).await;
            let is_granted = result.is_granted();
            let is_forbidden = result.is_forbidden();
            children_results.push(result);

            if is_forbidden {
                return PolicyEvalResult::Combined {
                    policy_type: self.policy_type(),
                    operation: CombineOp::Or,
                    children: children_results,
                    outcome: false,
                };
            }

            if policy_index < self.veto_capable_count {
                veto_prefix_granted |= is_granted;
                if policy_index + 1 == self.veto_capable_count && veto_prefix_granted {
                    return PolicyEvalResult::Combined {
                        policy_type: self.policy_type(),
                        operation: CombineOp::Or,
                        children: children_results,
                        outcome: true,
                    };
                }
            } else if is_granted {
                return PolicyEvalResult::Combined {
                    policy_type: self.policy_type(),
                    operation: CombineOp::Or,
                    children: children_results,
                    outcome: true,
                };
            }
        }

        PolicyEvalResult::Combined {
            policy_type: self.policy_type(),
            operation: CombineOp::Or,
            children: children_results,
            outcome: false,
        }
    }

    async fn evaluate_batch<'item>(&self, ctx: &BatchEvalCtx<'item, D>) -> Vec<PolicyEvalResult> {
        let mut children_by_item = vec![Vec::new(); ctx.items.len()];
        let mut results = vec![None; ctx.items.len()];
        let mut pending = (0..ctx.items.len()).collect::<Vec<_>>();
        let mut veto_prefix_granted = vec![false; ctx.items.len()];

        for (policy_index, policy) in self.policies.iter().enumerate() {
            if pending.is_empty() {
                break;
            }

            let batch_items = pending
                .iter()
                .map(|&index| PolicyBatchItem {
                    resource: ctx.items[index].resource,
                })
                .collect::<Vec<_>>();
            let batch_ctx = BatchEvalCtx {
                session: ctx.session,
                subject: ctx.subject,
                action: ctx.action,
                context: ctx.context,
                items: &batch_items,
                policy_type: policy.policy_type(),
            };
            let child_results = policy.evaluate_batch(&batch_ctx).await;

            if child_results.len() != pending.len() {
                for index in pending.drain(..) {
                    children_by_item[index].push(PolicyEvalResult::not_applicable(
                        policy.policy_type(),
                        "Policy batch result count did not match input count",
                    ));
                    results[index] = Some(PolicyEvalResult::Combined {
                        policy_type: self.policy_type(),
                        operation: CombineOp::Or,
                        children: std::mem::take(&mut children_by_item[index]),
                        outcome: false,
                    });
                }
                break;
            }

            let mut still_pending = Vec::new();
            for (index, child_result) in pending.into_iter().zip(child_results) {
                let is_granted = child_result.is_granted();
                let is_forbidden = child_result.is_forbidden();
                children_by_item[index].push(child_result);

                if is_forbidden {
                    results[index] = Some(PolicyEvalResult::Combined {
                        policy_type: self.policy_type(),
                        operation: CombineOp::Or,
                        children: std::mem::take(&mut children_by_item[index]),
                        outcome: false,
                    });
                } else if policy_index < self.veto_capable_count {
                    veto_prefix_granted[index] |= is_granted;
                    if policy_index + 1 == self.veto_capable_count && veto_prefix_granted[index] {
                        results[index] = Some(PolicyEvalResult::Combined {
                            policy_type: self.policy_type(),
                            operation: CombineOp::Or,
                            children: std::mem::take(&mut children_by_item[index]),
                            outcome: true,
                        });
                    } else {
                        still_pending.push(index);
                    }
                } else if is_granted {
                    results[index] = Some(PolicyEvalResult::Combined {
                        policy_type: self.policy_type(),
                        operation: CombineOp::Or,
                        children: std::mem::take(&mut children_by_item[index]),
                        outcome: true,
                    });
                } else {
                    still_pending.push(index);
                }
            }
            pending = still_pending;
        }

        for index in pending {
            results[index] = Some(PolicyEvalResult::Combined {
                policy_type: self.policy_type(),
                operation: CombineOp::Or,
                children: std::mem::take(&mut children_by_item[index]),
                outcome: false,
            });
        }

        results
            .into_iter()
            .map(|result| {
                result.unwrap_or_else(|| {
                    PolicyEvalResult::not_applicable(
                        self.policy_type(),
                        "Batch item was not evaluated",
                    )
                })
            })
            .collect()
    }
}

/// Inverts the decision of an inner policy.
pub struct NotPolicy<D: PolicyDomain> {
    policy: Arc<dyn Policy<D>>,
}

impl<D: PolicyDomain> NotPolicy<D> {
    /// Creates a new `NotPolicy` that inverts the given policy's decision.
    pub fn new(policy: impl Policy<D> + 'static) -> Self {
        Self {
            policy: Arc::new(policy),
        }
    }
}

#[async_trait]
impl<D: PolicyDomain> Policy<D> for NotPolicy<D> {
    fn policy_type(&self) -> std::borrow::Cow<'static, str> {
        std::borrow::Cow::Borrowed("NotPolicy")
    }

    fn effect(&self) -> Effect {
        Effect::from_capabilities(true, self.policy.effect().can_forbid())
    }

    async fn evaluate(&self, ctx: &EvalCtx<'_, D>) -> PolicyEvalResult {
        let inner_ctx = EvalCtx {
            session: ctx.session,
            subject: ctx.subject,
            action: ctx.action,
            resource: ctx.resource,
            context: ctx.context,
            policy_type: self.policy.policy_type(),
        };
        let inner_result = self.policy.evaluate(&inner_ctx).await;
        let is_forbidden = inner_result.is_forbidden();
        let is_granted = inner_result.is_granted();

        PolicyEvalResult::Combined {
            policy_type: Policy::<D>::policy_type(self),
            operation: CombineOp::Not,
            children: vec![inner_result],
            outcome: !is_forbidden && !is_granted,
        }
    }

    async fn evaluate_batch<'item>(&self, ctx: &BatchEvalCtx<'item, D>) -> Vec<PolicyEvalResult> {
        let inner_ctx = BatchEvalCtx {
            session: ctx.session,
            subject: ctx.subject,
            action: ctx.action,
            context: ctx.context,
            items: ctx.items,
            policy_type: self.policy.policy_type(),
        };
        let inner_results = self.policy.evaluate_batch(&inner_ctx).await;

        if inner_results.len() != ctx.items.len() {
            return ctx
                .items
                .iter()
                .map(|_| {
                    PolicyEvalResult::not_applicable(
                        self.policy_type(),
                        "Policy batch result count did not match input count",
                    )
                })
                .collect();
        }

        inner_results
            .into_iter()
            .map(|inner_result| {
                let is_forbidden = inner_result.is_forbidden();
                let is_granted = inner_result.is_granted();
                PolicyEvalResult::Combined {
                    policy_type: self.policy_type(),
                    operation: CombineOp::Not,
                    children: vec![inner_result],
                    outcome: !is_forbidden && !is_granted,
                }
            })
            .collect()
    }
}