Skip to main content

id_effect_authz/
policy.rs

1//! Policies: a [`Policy<Res>`](Policy) evaluates a [`CurrentPrincipal`] against a resource `Res`
2//! as an effect returning a [`Decision`].
3//!
4//! Policies compose with [`PolicyExt::and`], [`PolicyExt::or`], [`PolicyExt::negate`],
5//! [`all_of`] and [`any_of`]. Simple predicates come from [`predicate`]; a policy that has to
6//! look something up (an ACL row, a feature flag) is an effect, built with [`from_effect`].
7//!
8//! A policy that needs capabilities (a SQL client, a cache) receives them when it is
9//! constructed, typically in a [`Layer`](id_effect::Layer), so evaluating it needs nothing more:
10//! its effect has the empty environment.
11//!
12//! ```
13//! use id_effect::Exit;
14//! use id_effect_authz::{
15//!   BasicPrincipal, CurrentPrincipal, Decision, Policy, PolicyExt, predicate, require_role,
16//! };
17//!
18//! struct Invoice {
19//!   amount: u64,
20//! }
21//!
22//! let approve = require_role("accountant")
23//!   .and(predicate("amount above the approval limit", |_, inv: &Invoice| inv.amount <= 10_000));
24//!
25//! let alice = CurrentPrincipal::new(BasicPrincipal::new("alice").with_role("accountant"));
26//! let small = approve.evaluate(&alice, &Invoice { amount: 500 });
27//! assert_eq!(small.block_on(), Exit::Success(Decision::Allow));
28//! let large = approve.evaluate(&alice, &Invoice { amount: 50_000 });
29//! assert!(matches!(large.block_on(), Exit::Success(Decision::Deny(_))));
30//! ```
31
32use std::fmt;
33use std::sync::Arc;
34
35use id_effect::observability::posture::record_dangerous;
36use id_effect::{Effect, HList, Selector, need, succeed};
37
38use crate::principal::CurrentPrincipal;
39use crate::resource::{TenantScope, scoped};
40
41/// Why a policy denied: a human-readable reason and, when evaluated by name through
42/// [`Policies`](crate::Policies), the policy's name.
43#[derive(Clone, Debug, PartialEq, Eq, Hash)]
44pub struct Denial {
45  reason: String,
46  policy: Option<String>,
47}
48
49impl Denial {
50  /// A denial with `reason`.
51  pub fn new(reason: impl Into<String>) -> Self {
52    Self {
53      reason: reason.into(),
54      policy: None,
55    }
56  }
57
58  /// The reason.
59  pub fn reason(&self) -> &str {
60    &self.reason
61  }
62
63  /// The named policy that denied, when known.
64  pub fn policy(&self) -> Option<&str> {
65    self.policy.as_deref()
66  }
67
68  /// This denial attributed to the policy `name` (kept when already attributed).
69  #[must_use]
70  pub fn attributed_to(mut self, name: &str) -> Self {
71    if self.policy.is_none() {
72      self.policy = Some(name.to_owned());
73    }
74    self
75  }
76}
77
78impl fmt::Display for Denial {
79  fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
80    match &self.policy {
81      Some(name) => write!(f, "{name}: {}", self.reason),
82      None => f.write_str(&self.reason),
83    }
84  }
85}
86
87/// The outcome of evaluating a policy.
88#[derive(Clone, Debug, PartialEq, Eq, Hash)]
89pub enum Decision {
90  /// Access is granted.
91  Allow,
92  /// Access is refused, with the reason.
93  Deny(Denial),
94}
95
96impl Decision {
97  /// A denial with `reason`.
98  pub fn deny(reason: impl Into<String>) -> Self {
99    Self::Deny(Denial::new(reason))
100  }
101
102  /// [`Allow`](Decision::Allow) when `allowed`, else a denial with `reason`.
103  pub fn allow_if(allowed: bool, reason: impl Into<String>) -> Self {
104    if allowed {
105      Self::Allow
106    } else {
107      Self::deny(reason)
108    }
109  }
110
111  /// Whether access is granted.
112  pub fn is_allowed(&self) -> bool {
113    matches!(self, Self::Allow)
114  }
115
116  /// Whether access is refused.
117  pub fn is_denied(&self) -> bool {
118    !self.is_allowed()
119  }
120
121  /// `Ok(())` when allowed; [`AuthzError::Unauthenticated`] when denied to an anonymous
122  /// `principal`, [`AuthzError::Denied`] otherwise.
123  pub fn into_result(self, principal: &CurrentPrincipal) -> Result<(), AuthzError> {
124    match self {
125      Self::Allow => Ok(()),
126      Self::Deny(_) if !principal.is_authenticated() => Err(AuthzError::Unauthenticated),
127      Self::Deny(denial) => Err(AuthzError::Denied(denial)),
128    }
129  }
130}
131
132/// Authorization failures.
133#[derive(Clone, Debug, PartialEq, Eq, Hash)]
134#[non_exhaustive]
135pub enum AuthzError {
136  /// The principal is anonymous and the policy denied: authenticate first (HTTP 401).
137  Unauthenticated,
138  /// The policy denied an authenticated principal (HTTP 403).
139  Denied(Denial),
140  /// No policy is registered under this name.
141  UnknownPolicy(String),
142  /// The named policy exists for another resource type.
143  ResourceMismatch {
144    /// The policy name.
145    policy: String,
146    /// The resource type the policy was registered for.
147    expected: &'static str,
148    /// The resource type it was evaluated with.
149    found: &'static str,
150  },
151  /// Evaluating the policy failed (a lookup it depends on failed).
152  Evaluation(String),
153}
154
155impl AuthzError {
156  /// The HTTP status a route guard answers with: 401, 403 or 500.
157  pub fn http_status(&self) -> u16 {
158    match self {
159      Self::Unauthenticated => 401,
160      Self::Denied(_) => 403,
161      Self::UnknownPolicy(_) | Self::ResourceMismatch { .. } | Self::Evaluation(_) => 500,
162    }
163  }
164}
165
166impl fmt::Display for AuthzError {
167  fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
168    match self {
169      Self::Unauthenticated => f.write_str("authentication required"),
170      Self::Denied(denial) => write!(f, "forbidden: {denial}"),
171      Self::UnknownPolicy(name) => write!(f, "unknown policy `{name}`"),
172      Self::ResourceMismatch {
173        policy,
174        expected,
175        found,
176      } => write!(
177        f,
178        "policy `{policy}` is defined for `{expected}`, evaluated with `{found}`"
179      ),
180      Self::Evaluation(msg) => write!(f, "policy evaluation failed: {msg}"),
181    }
182  }
183}
184
185impl std::error::Error for AuthzError {}
186
187/// The effect a policy evaluates to.
188pub type PolicyEffect = Effect<Decision, AuthzError>;
189
190/// A rule deciding whether a principal may act on a resource of type `Res` (`()` for rules that
191/// look only at the principal).
192///
193/// The returned effect is what runs. A policy that only inspects its arguments may decide while
194/// building it and return a ready effect; one that performs a lookup returns that lookup.
195pub trait Policy<Res: ?Sized>: Send + Sync + 'static {
196  /// Evaluate the policy for `principal` acting on `resource`.
197  fn evaluate(&self, principal: &CurrentPrincipal, resource: &Res) -> PolicyEffect;
198
199  /// The decision without an effect, for a policy that decides from its arguments alone:
200  /// `Some` of the decision [`evaluate`](Self::evaluate) yields, or `None` (the default) to run
201  /// [`evaluate`](Self::evaluate). A route guard (feature `axum`) without audit events tries it
202  /// first, so a pure policy decides without the effect runtime.
203  fn decide_now(&self, principal: &CurrentPrincipal, resource: &Res) -> Option<Decision> {
204    let _ = (principal, resource);
205    None
206  }
207
208  /// Whether the policy opted out of the automatic tenant match
209  /// ([`PolicyExt::dangerous_cross_tenant`]); `false` for every other policy.
210  fn crosses_tenants(&self) -> bool {
211    false
212  }
213}
214
215/// A shared, type-erased policy over `Res`.
216pub type BoxPolicy<Res> = Arc<dyn Policy<Res>>;
217
218impl<Res: ?Sized, P: Policy<Res> + ?Sized> Policy<Res> for Arc<P> {
219  fn evaluate(&self, principal: &CurrentPrincipal, resource: &Res) -> PolicyEffect {
220    (**self).evaluate(principal, resource)
221  }
222
223  fn decide_now(&self, principal: &CurrentPrincipal, resource: &Res) -> Option<Decision> {
224    (**self).decide_now(principal, resource)
225  }
226
227  fn crosses_tenants(&self) -> bool {
228    (**self).crosses_tenants()
229  }
230}
231
232impl<Res: ?Sized, P: Policy<Res> + ?Sized> Policy<Res> for Box<P> {
233  fn evaluate(&self, principal: &CurrentPrincipal, resource: &Res) -> PolicyEffect {
234    (**self).evaluate(principal, resource)
235  }
236
237  fn decide_now(&self, principal: &CurrentPrincipal, resource: &Res) -> Option<Decision> {
238    (**self).decide_now(principal, resource)
239  }
240
241  fn crosses_tenants(&self) -> bool {
242    (**self).crosses_tenants()
243  }
244}
245
246/// Combinators for policies.
247///
248/// The trait does not name the resource type: most policies ([`require_role`], [`allow_all`],
249/// `Rbac::require`, claim policies) apply to every resource, and the combination is a
250/// [`Policy<Res>`](Policy) for each `Res` both sides accept, fixed where it is used.
251pub trait PolicyExt: Sized + Send + Sync + 'static {
252  /// Allows when both allow; `other` runs only when `self` allows.
253  fn and<P>(self, other: P) -> And<Self, P> {
254    And(self, other)
255  }
256
257  /// Allows when either allows; `other` runs only when `self` denies (its denial is kept).
258  fn or<P>(self, other: P) -> Or<Self, P> {
259    Or(self, other)
260  }
261
262  /// Allows when `self` denies; denies with `reason` when it allows.
263  fn negate(self, reason: impl Into<String>) -> Not<Self> {
264    Not(self, reason.into())
265  }
266
267  /// This policy over `Res`, shared and type-erased.
268  fn boxed<Res: ?Sized>(self) -> BoxPolicy<Res>
269  where
270    Self: Policy<Res>,
271  {
272    Arc::new(self)
273  }
274
275  /// This policy without the automatic tenant match: defined by name or run with
276  /// [`check_with`] / [`authorize_with`], it decides on a [`Tenanted`](crate::Tenanted) resource
277  /// for principals of any tenant. `reason` says who needs that (support tooling, a platform
278  /// operator) and is kept on the policy for review.
279  ///
280  /// A dangerous opt-out (ADR 0013 R10): the call records
281  /// `id_effect_authz::PolicyExt::dangerous_cross_tenant` in the posture registry. It applies to
282  /// the policy it wraps as a whole, so it has to be the outermost combinator.
283  fn dangerous_cross_tenant(self, reason: impl Into<String>) -> CrossTenant<Self> {
284    record_dangerous(
285      "id_effect_authz::PolicyExt::dangerous_cross_tenant",
286      "M19: a policy over tenant-scoped resources decides for principals of other tenants",
287    );
288    CrossTenant {
289      policy: self,
290      reason: reason.into(),
291    }
292  }
293}
294
295impl<P: Sized + Send + Sync + 'static> PolicyExt for P {}
296
297/// See [`PolicyExt::dangerous_cross_tenant`].
298#[derive(Clone, Debug)]
299pub struct CrossTenant<P> {
300  policy: P,
301  reason: String,
302}
303
304impl<P> CrossTenant<P> {
305  /// Why the policy crosses tenants.
306  pub fn reason(&self) -> &str {
307    &self.reason
308  }
309}
310
311impl<Res: ?Sized, P: Policy<Res>> Policy<Res> for CrossTenant<P> {
312  fn evaluate(&self, principal: &CurrentPrincipal, resource: &Res) -> PolicyEffect {
313    self.policy.evaluate(principal, resource)
314  }
315
316  fn decide_now(&self, principal: &CurrentPrincipal, resource: &Res) -> Option<Decision> {
317    self.policy.decide_now(principal, resource)
318  }
319
320  fn crosses_tenants(&self) -> bool {
321    true
322  }
323}
324
325/// See [`PolicyExt::and`].
326#[derive(Clone, Debug)]
327pub struct And<A, B>(A, B);
328
329impl<Res: ?Sized, A: Policy<Res>, B: Policy<Res>> Policy<Res> for And<A, B> {
330  fn evaluate(&self, principal: &CurrentPrincipal, resource: &Res) -> PolicyEffect {
331    let second = self.1.evaluate(principal, resource);
332    self
333      .0
334      .evaluate(principal, resource)
335      .flat_map(move |first| match first {
336        Decision::Allow => second,
337        denied => succeed(denied),
338      })
339  }
340
341  /// Both sides decided now (in [`evaluate`](Policy::evaluate)'s order, the second first).
342  fn decide_now(&self, principal: &CurrentPrincipal, resource: &Res) -> Option<Decision> {
343    let second = self.1.decide_now(principal, resource)?;
344    Some(match self.0.decide_now(principal, resource)? {
345      Decision::Allow => second,
346      denied => denied,
347    })
348  }
349}
350
351/// See [`PolicyExt::or`].
352#[derive(Clone, Debug)]
353pub struct Or<A, B>(A, B);
354
355impl<Res: ?Sized, A: Policy<Res>, B: Policy<Res>> Policy<Res> for Or<A, B> {
356  fn evaluate(&self, principal: &CurrentPrincipal, resource: &Res) -> PolicyEffect {
357    let second = self.1.evaluate(principal, resource);
358    self
359      .0
360      .evaluate(principal, resource)
361      .flat_map(move |first| match first {
362        Decision::Allow => succeed(Decision::Allow),
363        Decision::Deny(_) => second,
364      })
365  }
366
367  /// Both sides decided now (in [`evaluate`](Policy::evaluate)'s order, the second first).
368  fn decide_now(&self, principal: &CurrentPrincipal, resource: &Res) -> Option<Decision> {
369    let second = self.1.decide_now(principal, resource)?;
370    Some(match self.0.decide_now(principal, resource)? {
371      Decision::Allow => Decision::Allow,
372      Decision::Deny(_) => second,
373    })
374  }
375}
376
377/// See [`PolicyExt::negate`].
378#[derive(Clone, Debug)]
379pub struct Not<A>(A, String);
380
381impl<Res: ?Sized, A: Policy<Res>> Policy<Res> for Not<A> {
382  fn evaluate(&self, principal: &CurrentPrincipal, resource: &Res) -> PolicyEffect {
383    let reason = self.1.clone();
384    self
385      .0
386      .evaluate(principal, resource)
387      .map(move |inner| match inner {
388        Decision::Allow => Decision::deny(reason),
389        Decision::Deny(_) => Decision::Allow,
390      })
391  }
392
393  fn decide_now(&self, principal: &CurrentPrincipal, resource: &Res) -> Option<Decision> {
394    Some(match self.0.decide_now(principal, resource)? {
395      Decision::Allow => Decision::deny(self.1.clone()),
396      Decision::Deny(_) => Decision::Allow,
397    })
398  }
399}
400
401/// Allows when every policy allows (in order, stopping at the first denial); an empty list
402/// allows.
403pub fn all_of<Res: ?Sized + 'static>(policies: Vec<BoxPolicy<Res>>) -> AllOf<Res> {
404  AllOf(policies)
405}
406
407/// See [`all_of`].
408pub struct AllOf<Res: ?Sized>(Vec<BoxPolicy<Res>>);
409
410impl<Res: ?Sized + 'static> Policy<Res> for AllOf<Res> {
411  fn evaluate(&self, principal: &CurrentPrincipal, resource: &Res) -> PolicyEffect {
412    let steps: Vec<PolicyEffect> = self
413      .0
414      .iter()
415      .map(|p| p.evaluate(principal, resource))
416      .collect();
417    steps
418      .into_iter()
419      .rev()
420      .fold(succeed(Decision::Allow), |rest, step| {
421        step.flat_map(move |d| match d {
422          Decision::Allow => rest,
423          denied => succeed(denied),
424        })
425      })
426  }
427}
428
429/// Allows when any policy allows (in order, stopping at the first allow); when all deny, the
430/// last denial is kept; an empty list denies.
431pub fn any_of<Res: ?Sized + 'static>(policies: Vec<BoxPolicy<Res>>) -> AnyOf<Res> {
432  AnyOf(policies)
433}
434
435/// See [`any_of`].
436pub struct AnyOf<Res: ?Sized>(Vec<BoxPolicy<Res>>);
437
438impl<Res: ?Sized + 'static> Policy<Res> for AnyOf<Res> {
439  fn evaluate(&self, principal: &CurrentPrincipal, resource: &Res) -> PolicyEffect {
440    let mut steps: Vec<PolicyEffect> = self
441      .0
442      .iter()
443      .map(|p| p.evaluate(principal, resource))
444      .collect();
445    let Some(last) = steps.pop() else {
446      return succeed(Decision::deny("no policy allowed"));
447    };
448    steps.into_iter().rev().fold(last, |rest, step| {
449      step.flat_map(move |d| match d {
450        Decision::Allow => succeed(Decision::Allow),
451        Decision::Deny(_) => rest,
452      })
453    })
454  }
455}
456
457impl<Res: ?Sized> fmt::Debug for AllOf<Res> {
458  fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
459    f.debug_tuple("AllOf").field(&self.0.len()).finish()
460  }
461}
462
463impl<Res: ?Sized> fmt::Debug for AnyOf<Res> {
464  fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
465    f.debug_tuple("AnyOf").field(&self.0.len()).finish()
466  }
467}
468
469/// A policy that always allows.
470pub fn allow_all() -> Constant {
471  Constant(Decision::Allow)
472}
473
474/// A policy that always denies with `reason`.
475pub fn deny_all(reason: impl Into<String>) -> Constant {
476  Constant(Decision::deny(reason))
477}
478
479/// See [`allow_all`] and [`deny_all`].
480#[derive(Clone, Debug)]
481pub struct Constant(Decision);
482
483impl<Res: ?Sized> Policy<Res> for Constant {
484  fn evaluate(&self, _: &CurrentPrincipal, _: &Res) -> PolicyEffect {
485    succeed(self.0.clone())
486  }
487
488  fn decide_now(&self, _: &CurrentPrincipal, _: &Res) -> Option<Decision> {
489    Some(self.0.clone())
490  }
491}
492
493/// Allows any authenticated principal (denies [`Anonymous`](crate::Anonymous)).
494pub fn authenticated() -> Authenticated {
495  Authenticated
496}
497
498/// See [`authenticated`].
499#[derive(Clone, Copy, Debug)]
500pub struct Authenticated;
501
502impl Authenticated {
503  fn decision(principal: &CurrentPrincipal) -> Decision {
504    if principal.is_authenticated() {
505      Decision::Allow
506    } else {
507      Decision::deny("authentication required")
508    }
509  }
510}
511
512impl<Res: ?Sized> Policy<Res> for Authenticated {
513  fn evaluate(&self, principal: &CurrentPrincipal, _: &Res) -> PolicyEffect {
514    succeed(Self::decision(principal))
515  }
516
517  fn decide_now(&self, principal: &CurrentPrincipal, _: &Res) -> Option<Decision> {
518    Some(Self::decision(principal))
519  }
520}
521
522/// Allows a principal holding `role` directly (use [`Rbac::require_role`](crate::Rbac::require_role)
523/// to honour role inheritance).
524pub fn require_role(role: impl Into<String>) -> RequireRole {
525  RequireRole(vec![role.into()])
526}
527
528/// Allows a principal holding at least one of `roles` directly.
529pub fn require_any_role<S: Into<String>>(roles: impl IntoIterator<Item = S>) -> RequireRole {
530  RequireRole(roles.into_iter().map(Into::into).collect())
531}
532
533/// See [`require_role`] and [`require_any_role`].
534#[derive(Clone, Debug)]
535pub struct RequireRole(Vec<String>);
536
537impl RequireRole {
538  fn decision(&self, principal: &CurrentPrincipal) -> Decision {
539    if self.0.iter().any(|r| principal.has_role(r)) {
540      Decision::Allow
541    } else {
542      Decision::deny(format!("requires role {}", self.0.join(" or ")))
543    }
544  }
545}
546
547impl<Res: ?Sized> Policy<Res> for RequireRole {
548  fn evaluate(&self, principal: &CurrentPrincipal, _: &Res) -> PolicyEffect {
549    succeed(self.decision(principal))
550  }
551
552  fn decide_now(&self, principal: &CurrentPrincipal, _: &Res) -> Option<Decision> {
553    Some(self.decision(principal))
554  }
555}
556
557/// A policy from a synchronous predicate: allows when `check(principal, resource)` holds, else
558/// denies with `reason`.
559pub fn predicate<Res, F>(reason: impl Into<String>, check: F) -> PredicatePolicy<F>
560where
561  Res: ?Sized,
562  F: Fn(&CurrentPrincipal, &Res) -> bool + Send + Sync + 'static,
563{
564  PredicatePolicy {
565    reason: reason.into(),
566    check,
567  }
568}
569
570/// See [`predicate`].
571#[derive(Clone)]
572pub struct PredicatePolicy<F> {
573  reason: String,
574  check: F,
575}
576
577impl<F> fmt::Debug for PredicatePolicy<F> {
578  fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
579    f.debug_struct("PredicatePolicy")
580      .field("reason", &self.reason)
581      .finish()
582  }
583}
584
585impl<Res, F> Policy<Res> for PredicatePolicy<F>
586where
587  Res: ?Sized,
588  F: Fn(&CurrentPrincipal, &Res) -> bool + Send + Sync + 'static,
589{
590  fn evaluate(&self, principal: &CurrentPrincipal, resource: &Res) -> PolicyEffect {
591    succeed(Decision::allow_if(
592      (self.check)(principal, resource),
593      self.reason.as_str(),
594    ))
595  }
596
597  fn decide_now(&self, principal: &CurrentPrincipal, resource: &Res) -> Option<Decision> {
598    Some(Decision::allow_if(
599      (self.check)(principal, resource),
600      self.reason.as_str(),
601    ))
602  }
603}
604
605/// A policy from a function returning the decision effect (for policies that look something
606/// up). Copy what the effect needs out of `resource`: the effect outlives the borrow.
607pub fn from_effect<Res, F>(evaluate: F) -> EffectPolicy<F>
608where
609  Res: ?Sized,
610  F: Fn(&CurrentPrincipal, &Res) -> PolicyEffect + Send + Sync + 'static,
611{
612  EffectPolicy(evaluate)
613}
614
615/// See [`from_effect`].
616#[derive(Clone)]
617pub struct EffectPolicy<F>(F);
618
619impl<F> fmt::Debug for EffectPolicy<F> {
620  fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
621    f.write_str("EffectPolicy")
622  }
623}
624
625impl<Res, F> Policy<Res> for EffectPolicy<F>
626where
627  Res: ?Sized,
628  F: Fn(&CurrentPrincipal, &Res) -> PolicyEffect + Send + Sync + 'static,
629{
630  fn evaluate(&self, principal: &CurrentPrincipal, resource: &Res) -> PolicyEffect {
631    (self.0)(principal, resource)
632  }
633}
634
635/// Evaluates `policy` for the [`CurrentPrincipal`] in `R` acting on `resource`, behind the
636/// tenant check ([`TenantScope`]) unless the policy
637/// [crosses tenants](PolicyExt::dangerous_cross_tenant).
638pub fn check_with<P, Res, R, I>(policy: P, resource: Res) -> Effect<Decision, AuthzError, R>
639where
640  P: Policy<Res>,
641  Res: TenantScope + Send + Sync + 'static,
642  R: Selector<CurrentPrincipal, I> + HList,
643{
644  let policy = scoped(policy);
645  need::<CurrentPrincipal>().flat_map(move |p| policy.evaluate(&p, &resource).narrow())
646}
647
648/// Like [`check_with`], failing with [`AuthzError::Denied`] (or
649/// [`AuthzError::Unauthenticated`]) instead of returning a denial.
650pub fn authorize_with<P, Res, R, I>(policy: P, resource: Res) -> Effect<(), AuthzError, R>
651where
652  P: Policy<Res>,
653  Res: TenantScope + Send + Sync + 'static,
654  R: Selector<CurrentPrincipal, I> + HList,
655{
656  let policy = scoped(policy);
657  need::<CurrentPrincipal>().flat_map(move |p| {
658    policy
659      .evaluate(&p, &resource)
660      .flat_map(move |d| into_effect(d, &p))
661      .narrow()
662  })
663}
664
665/// The decision as an effect that fails when it denies.
666pub(crate) fn into_effect(
667  decision: Decision,
668  principal: &CurrentPrincipal,
669) -> Effect<(), AuthzError> {
670  match decision.into_result(principal) {
671    Ok(()) => succeed(()),
672    Err(e) => id_effect::fail(e),
673  }
674}
675
676#[cfg(test)]
677mod tests {
678  use super::*;
679  use crate::principal::{BasicPrincipal, principal_env};
680  use id_effect::{Cause, Exit, fail};
681
682  fn alice() -> CurrentPrincipal {
683    CurrentPrincipal::new(BasicPrincipal::new("alice").with_role("accountant"))
684  }
685
686  fn decide<P: Policy<()>>(policy: &P, who: &CurrentPrincipal) -> Decision {
687    match policy.evaluate(who, &()).block_on() {
688      Exit::Success(d) => d,
689      other => panic!("unexpected exit: {other:?}"),
690    }
691  }
692
693  #[test]
694  fn constants_and_authenticated() {
695    assert_eq!(decide(&allow_all(), &alice()), Decision::Allow);
696    assert_eq!(
697      decide(&deny_all("closed"), &alice()),
698      Decision::deny("closed")
699    );
700    assert!(decide(&authenticated(), &alice()).is_allowed());
701    assert!(decide(&authenticated(), &CurrentPrincipal::anonymous()).is_denied());
702  }
703
704  #[test]
705  fn roles_must_be_held() {
706    assert!(decide(&require_role("accountant"), &alice()).is_allowed());
707    let Decision::Deny(denial) = decide(&require_any_role(["owner", "admin"]), &alice()) else {
708      panic!("expected a denial")
709    };
710    assert_eq!(denial.reason(), "requires role owner or admin");
711    assert_eq!(denial.policy(), None);
712  }
713
714  #[test]
715  fn and_or_not_short_circuit() {
716    let yes = allow_all();
717    let no = deny_all("no");
718    assert!(decide(&yes.clone().and(yes.clone()), &alice()).is_allowed());
719    assert_eq!(
720      decide(&no.clone().and(yes.clone()), &alice()),
721      Decision::deny("no")
722    );
723    assert_eq!(
724      decide(&yes.clone().and(deny_all("second")), &alice()),
725      Decision::deny("second")
726    );
727    assert!(decide(&no.clone().or(yes.clone()), &alice()).is_allowed());
728    assert!(decide(&yes.clone().or(no.clone()), &alice()).is_allowed());
729    assert_eq!(
730      decide(&no.clone().or(deny_all("last")), &alice()),
731      Decision::deny("last")
732    );
733    assert_eq!(
734      decide(&yes.negate("inverted"), &alice()),
735      Decision::deny("inverted")
736    );
737    assert!(decide(&no.negate("unused"), &alice()).is_allowed());
738  }
739
740  #[test]
741  fn all_of_and_any_of() {
742    let both = all_of(vec![
743      allow_all().boxed(),
744      require_role("accountant").boxed(),
745    ]);
746    assert!(decide(&both, &alice()).is_allowed());
747    let one_denies = all_of(vec![
748      allow_all().boxed(),
749      deny_all("x").boxed(),
750      deny_all("y").boxed(),
751    ]);
752    assert_eq!(decide(&one_denies, &alice()), Decision::deny("x"));
753    assert!(decide(&all_of::<()>(vec![]), &alice()).is_allowed());
754    let either = any_of(vec![deny_all("a").boxed(), allow_all().boxed()]);
755    assert!(decide(&either, &alice()).is_allowed());
756    let none = any_of(vec![deny_all("a").boxed(), deny_all("b").boxed()]);
757    assert_eq!(decide(&none, &alice()), Decision::deny("b"));
758    assert_eq!(
759      decide(&any_of::<()>(vec![]), &alice()),
760      Decision::deny("no policy allowed")
761    );
762    assert_eq!(format!("{both:?} {none:?}"), "AllOf(2) AnyOf(2)");
763  }
764
765  #[test]
766  fn pure_policies_decide_now_as_they_evaluate() {
767    let pure: Vec<BoxPolicy<()>> = vec![
768      allow_all().boxed(),
769      deny_all("closed").boxed(),
770      authenticated().boxed(),
771      require_role("accountant").boxed(),
772      require_any_role(["owner", "admin"]).boxed(),
773      predicate("never", |_: &CurrentPrincipal, _: &()| false).boxed(),
774      allow_all().and(deny_all("second")).boxed(),
775      deny_all("first").and(allow_all()).boxed(),
776      deny_all("a").or(require_role("accountant")).boxed(),
777      deny_all("a").or(deny_all("b")).boxed(),
778      require_role("accountant").negate("inverted").boxed(),
779      Box::new(deny_all("boxed")).boxed(),
780    ];
781    for who in [alice(), CurrentPrincipal::anonymous()] {
782      for policy in &pure {
783        assert_eq!(
784          policy.decide_now(&who, &()),
785          Some(decide(policy, &who)),
786          "{who:?}"
787        );
788      }
789    }
790    // A policy that has to run an effect (alone or inside a combinator) is left to `evaluate`.
791    let lookup = from_effect(|_: &CurrentPrincipal, _: &()| succeed(Decision::Allow));
792    assert_eq!(lookup.decide_now(&alice(), &()), None);
793    assert_eq!(
794      allow_all().and(lookup.clone()).decide_now(&alice(), &()),
795      None
796    );
797    assert_eq!(lookup.negate("x").decide_now(&alice(), &()), None);
798    assert_eq!(
799      all_of::<()>(vec![allow_all().boxed()]).decide_now(&alice(), &()),
800      None
801    );
802  }
803
804  #[test]
805  fn predicate_and_effect_policies() {
806    let even = predicate("odd", |_: &CurrentPrincipal, n: &u32| n.is_multiple_of(2));
807    assert!(even.evaluate(&alice(), &4).block_on() == Exit::Success(Decision::Allow));
808    assert_eq!(
809      even.evaluate(&alice(), &3).block_on(),
810      Exit::Success(Decision::deny("odd"))
811    );
812    assert!(format!("{even:?}").contains("odd"));
813
814    let lookup = from_effect(|p: &CurrentPrincipal, _: &()| {
815      let id = p.id().to_owned();
816      id_effect::sync(move || Decision::allow_if(id == "alice", "not alice"))
817    });
818    assert!(decide(&lookup, &alice()).is_allowed());
819    assert_eq!(format!("{lookup:?}"), "EffectPolicy");
820
821    let broken =
822      from_effect(|_: &CurrentPrincipal, _: &()| fail(AuthzError::Evaluation("db down".into())));
823    assert_eq!(
824      broken.evaluate(&alice(), &()).block_on(),
825      Exit::Failure(Cause::Fail(AuthzError::Evaluation("db down".into())))
826    );
827  }
828
829  #[test]
830  fn shared_policies_delegate() {
831    let shared: Arc<RequireRole> = Arc::new(require_role("accountant"));
832    assert!(decide(&shared, &alice()).is_allowed());
833    let boxed: Box<dyn Policy<()>> = Box::new(deny_all("boxed"));
834    assert_eq!(decide(&boxed, &alice()), Decision::deny("boxed"));
835  }
836
837  #[test]
838  fn decisions_and_denials() {
839    assert!(Decision::allow_if(true, "x").is_allowed());
840    let d = Denial::new("nope")
841      .attributed_to("p")
842      .attributed_to("ignored");
843    assert_eq!(d.policy(), Some("p"));
844    assert_eq!(d.to_string(), "p: nope");
845    assert_eq!(Denial::new("bare").to_string(), "bare");
846    assert_eq!(Decision::Allow.into_result(&alice()), Ok(()));
847    assert_eq!(
848      Decision::deny("no").into_result(&alice()),
849      Err(AuthzError::Denied(Denial::new("no")))
850    );
851    assert_eq!(
852      Decision::deny("no").into_result(&CurrentPrincipal::anonymous()),
853      Err(AuthzError::Unauthenticated)
854    );
855  }
856
857  #[test]
858  fn errors_display_and_map_to_http_status() {
859    let cases = [
860      (AuthzError::Unauthenticated, 401, "authentication required"),
861      (AuthzError::Denied(Denial::new("r")), 403, "forbidden: r"),
862      (
863        AuthzError::UnknownPolicy("p".into()),
864        500,
865        "unknown policy `p`",
866      ),
867      (
868        AuthzError::ResourceMismatch {
869          policy: "p".into(),
870          expected: "A",
871          found: "B",
872        },
873        500,
874        "policy `p` is defined for `A`, evaluated with `B`",
875      ),
876      (
877        AuthzError::Evaluation("io".into()),
878        500,
879        "policy evaluation failed: io",
880      ),
881    ];
882    for (err, status, text) in cases {
883      assert_eq!(err.http_status(), status);
884      assert_eq!(err.to_string(), text);
885    }
886  }
887
888  #[test]
889  fn check_and_authorize_read_the_principal_capability() {
890    let env = || principal_env(BasicPrincipal::new("alice").with_role("accountant"));
891    let checked = check_with(require_role("owner"), ()).provide_all(env());
892    assert_eq!(
893      checked.block_on(),
894      Exit::Success(Decision::deny("requires role owner"))
895    );
896    let ok = authorize_with(require_role("accountant"), ()).provide_all(env());
897    assert_eq!(ok.block_on(), Exit::Success(()));
898    let denied = authorize_with(require_role("owner"), ()).provide_all(env());
899    assert_eq!(
900      denied.block_on(),
901      Exit::Failure(Cause::Fail(AuthzError::Denied(Denial::new(
902        "requires role owner"
903      ))))
904    );
905    let anon = authorize_with(authenticated(), ()).provide_all(principal_env(crate::Anonymous));
906    assert_eq!(
907      anon.block_on(),
908      Exit::Failure(Cause::Fail(AuthzError::Unauthenticated))
909    );
910  }
911}