use crate::{
BatchEvalCtx, Decision, EvalCtx, GrantResult, Policy, PolicyDomain, PolicyEvalResult,
VetoPolicy, VetoResult,
};
use async_trait::async_trait;
use std::borrow::Cow;
use std::marker::PhantomData;
type SubjectPredicate<D> = Box<dyn Fn(&<D as PolicyDomain>::Subject) -> bool + Send + Sync>;
type ActionPredicate<D> = Box<dyn Fn(&<D as PolicyDomain>::Action) -> bool + Send + Sync>;
type ResourcePredicate<D> = Box<dyn Fn(&<D as PolicyDomain>::Resource) -> bool + Send + Sync>;
type ContextPredicate<D> = Box<dyn Fn(&<D as PolicyDomain>::Context) -> bool + Send + Sync>;
type WhenPredicate<D> = Box<
dyn Fn(
&<D as PolicyDomain>::Subject,
&<D as PolicyDomain>::Action,
&<D as PolicyDomain>::Resource,
&<D as PolicyDomain>::Context,
) -> bool
+ Send
+ Sync,
>;
mod sealed {
pub trait Sealed {}
}
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash)]
pub struct Unconditional;
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash)]
pub struct Conditional;
pub trait BuilderState: sealed::Sealed + Send + Sync + 'static {}
impl sealed::Sealed for Unconditional {}
impl sealed::Sealed for Conditional {}
impl BuilderState for Unconditional {}
impl BuilderState for Conditional {}
struct InternalPolicy<D: PolicyDomain> {
name: Cow<'static, str>,
subject_preds: Vec<SubjectPredicate<D>>,
action_preds: Vec<ActionPredicate<D>>,
resource_preds: Vec<ResourcePredicate<D>>,
context_preds: Vec<ContextPredicate<D>>,
when_preds: Vec<WhenPredicate<D>>,
_domain: PhantomData<D>,
}
impl<D: PolicyDomain> InternalPolicy<D> {
fn shared_axes_pass(
&self,
subject: &D::Subject,
action: &D::Action,
context: &D::Context,
) -> bool {
self.subject_preds.iter().all(|pred| pred(subject))
&& self.action_preds.iter().all(|pred| pred(action))
&& self.context_preds.iter().all(|pred| pred(context))
}
fn per_resource_axes_pass(
&self,
subject: &D::Subject,
action: &D::Action,
resource: &D::Resource,
context: &D::Context,
) -> bool {
self.resource_preds.iter().all(|pred| pred(resource))
&& self
.when_preds
.iter()
.all(|pred| pred(subject, action, resource, context))
}
fn build_result(&self, all_axes_pass: bool) -> GrantResult {
if all_axes_pass {
GrantResult::granted(self.name.clone(), Some("Policy allowed access".into()))
} else {
GrantResult::not_applicable(self.name.clone(), "Policy predicate did not match")
}
}
}
#[async_trait]
impl<D: PolicyDomain> Policy<D> for InternalPolicy<D> {
async fn evaluate(&self, ctx: &EvalCtx<'_, D>) -> GrantResult {
let pass = self.shared_axes_pass(ctx.subject, ctx.action, ctx.context)
&& self.per_resource_axes_pass(ctx.subject, ctx.action, ctx.resource, ctx.context);
self.build_result(pass)
}
async fn evaluate_batch<'item>(&self, ctx: &BatchEvalCtx<'item, D>) -> Vec<GrantResult> {
let n = ctx.items.len();
if n == 0 {
return Vec::new();
}
if !self.shared_axes_pass(ctx.subject, ctx.action, ctx.context) {
let result = self.build_result(false);
return std::iter::repeat_with(|| result.clone()).take(n).collect();
}
if self.resource_preds.is_empty() && self.when_preds.is_empty() {
let result = self.build_result(true);
return std::iter::repeat_with(|| result.clone()).take(n).collect();
}
ctx.items
.iter()
.map(|item| {
let pass = self.per_resource_axes_pass(
ctx.subject,
ctx.action,
item.resource,
ctx.context,
);
self.build_result(pass)
})
.collect()
}
fn policy_type(&self) -> Cow<'static, str> {
self.name.clone()
}
}
pub struct PolicyBuilder<D: PolicyDomain, S: BuilderState = Unconditional> {
name: Cow<'static, str>,
subject_preds: Vec<SubjectPredicate<D>>,
action_preds: Vec<ActionPredicate<D>>,
resource_preds: Vec<ResourcePredicate<D>>,
context_preds: Vec<ContextPredicate<D>>,
when_preds: Vec<WhenPredicate<D>>,
_state: PhantomData<(D, S)>,
}
impl<D: PolicyDomain> PolicyBuilder<D, Unconditional> {
pub fn new(name: impl Into<Cow<'static, str>>) -> Self {
Self {
name: name.into(),
subject_preds: Vec::new(),
action_preds: Vec::new(),
resource_preds: Vec::new(),
context_preds: Vec::new(),
when_preds: Vec::new(),
_state: PhantomData,
}
}
pub fn new_owned(name: impl Into<String>) -> Self {
Self::new(Cow::Owned(name.into()))
}
pub fn new_static(name: &'static str) -> Self {
Self::new(name)
}
pub fn allow_all(self) -> Box<dyn Policy<D>> {
self.into_policy()
}
pub fn forbid_all(self) -> Box<dyn VetoPolicy<D>> {
Box::new(PredicateVeto(self.into_policy()))
}
}
impl<D: PolicyDomain, S: BuilderState> PolicyBuilder<D, S> {
pub fn subjects<F>(mut self, pred: F) -> PolicyBuilder<D, Conditional>
where
F: Fn(&D::Subject) -> bool + Send + Sync + 'static,
{
self.subject_preds.push(Box::new(pred));
self.into_conditional()
}
pub fn actions<F>(mut self, pred: F) -> PolicyBuilder<D, Conditional>
where
F: Fn(&D::Action) -> bool + Send + Sync + 'static,
{
self.action_preds.push(Box::new(pred));
self.into_conditional()
}
pub fn resources<F>(mut self, pred: F) -> PolicyBuilder<D, Conditional>
where
F: Fn(&D::Resource) -> bool + Send + Sync + 'static,
{
self.resource_preds.push(Box::new(pred));
self.into_conditional()
}
pub fn context<F>(mut self, pred: F) -> PolicyBuilder<D, Conditional>
where
F: Fn(&D::Context) -> bool + Send + Sync + 'static,
{
self.context_preds.push(Box::new(pred));
self.into_conditional()
}
pub fn when<F>(mut self, pred: F) -> PolicyBuilder<D, Conditional>
where
F: Fn(&D::Subject, &D::Action, &D::Resource, &D::Context) -> bool + Send + Sync + 'static,
{
self.when_preds.push(Box::new(pred));
self.into_conditional()
}
fn into_conditional(self) -> PolicyBuilder<D, Conditional> {
PolicyBuilder {
name: self.name,
subject_preds: self.subject_preds,
action_preds: self.action_preds,
resource_preds: self.resource_preds,
context_preds: self.context_preds,
when_preds: self.when_preds,
_state: PhantomData,
}
}
fn into_policy(self) -> Box<dyn Policy<D>> {
Box::new(InternalPolicy {
name: self.name,
subject_preds: self.subject_preds,
action_preds: self.action_preds,
resource_preds: self.resource_preds,
context_preds: self.context_preds,
when_preds: self.when_preds,
_domain: PhantomData,
})
}
}
impl<D: PolicyDomain> PolicyBuilder<D, Conditional> {
pub fn build_veto(self) -> Box<dyn VetoPolicy<D>> {
Box::new(PredicateVeto(self.into_policy()))
}
pub fn build(self) -> Box<dyn Policy<D>> {
self.into_policy()
}
}
struct PredicateVeto<D: PolicyDomain>(Box<dyn Policy<D>>);
#[async_trait]
impl<D: PolicyDomain> VetoPolicy<D> for PredicateVeto<D> {
async fn evaluate(&self, ctx: &EvalCtx<'_, D>) -> VetoResult {
predicate_veto_result(self.0.evaluate(ctx).await)
}
async fn evaluate_batch<'item>(&self, ctx: &BatchEvalCtx<'item, D>) -> Vec<VetoResult> {
self.0
.evaluate_batch(ctx)
.await
.into_iter()
.map(predicate_veto_result)
.collect()
}
fn policy_type(&self) -> Cow<'static, str> {
self.0.policy_type()
}
}
pub(crate) fn predicate_veto_result(result: GrantResult) -> VetoResult {
let decision = result.decision();
let policy_type = match result.0 {
PolicyEvalResult::Granted { policy_type, .. }
| PolicyEvalResult::NotApplicable { policy_type, .. }
| PolicyEvalResult::Forbidden { policy_type, .. }
| PolicyEvalResult::Indeterminate { policy_type, .. }
| PolicyEvalResult::Combined { policy_type, .. } => policy_type,
};
match decision {
Decision::Grant => VetoResult::forbid(policy_type, "Policy forbids access"),
Decision::NotApplicable => VetoResult::pass(policy_type, "Policy predicate did not match"),
_ => VetoResult::indeterminate(policy_type, "Veto predicate could not be evaluated"),
}
}