use crate::capability::combined;
use crate::{
BatchEvalCtx, CombineOp, Decision, EvalCtx, GrantResult, Policy, PolicyBatchItem, PolicyDomain,
VetoPolicy, VetoResult,
};
use async_trait::async_trait;
use std::{borrow::Cow, sync::Arc};
#[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 {}
pub trait PolicyExt<D: PolicyDomain>: Policy<D> + Sized + 'static {
fn and<P: Policy<D> + 'static>(self, other: P) -> AndPolicy<D> {
AndPolicy {
name: Cow::Borrowed("AndPolicy"),
policies: vec![Arc::new(self), Arc::new(other)],
}
}
fn or<P: Policy<D> + 'static>(self, other: P) -> OrPolicy<D> {
OrPolicy {
name: Cow::Borrowed("OrPolicy"),
policies: vec![Arc::new(self), Arc::new(other)],
}
}
fn not(self) -> NotPolicy<D> {
NotPolicy::new(self)
}
fn boxed(self) -> Box<dyn Policy<D>> {
Box::new(self)
}
}
impl<D: PolicyDomain, P: Policy<D> + Sized + 'static> PolicyExt<D> for P {}
pub struct AndPolicy<D: PolicyDomain> {
name: Cow<'static, str>,
policies: Vec<Arc<dyn Policy<D>>>,
}
pub struct OrPolicy<D: PolicyDomain> {
name: Cow<'static, str>,
policies: Vec<Arc<dyn Policy<D>>>,
}
pub struct NotPolicy<D: PolicyDomain> {
name: Cow<'static, str>,
policy: Arc<dyn Policy<D>>,
}
impl<D: PolicyDomain> NotPolicy<D> {
pub fn new<P: Policy<D> + 'static>(policy: P) -> Self {
Self {
name: Cow::Borrowed("NotPolicy"),
policy: Arc::new(policy),
}
}
}
macro_rules! named {
($name:ident, $credit:literal) => {
impl<D: PolicyDomain> $name<D> {
#[doc = concat!("`\"", stringify!($name), "\"`)")]
#[doc = $credit]
#[must_use]
pub fn named(mut self, name: impl Into<Cow<'static, str>>) -> Self {
self.name = name.into();
self
}
}
};
}
named!(
NotPolicy,
"An inversion decides a grant as a whole, so this is the name \
[`crate::AccessEvaluation::granted_policy_type`] reports; name it after \
the rule it expresses."
);
macro_rules! constructor {
($name:ident, $policy:ident, $credit:literal) => {
impl<D: PolicyDomain> $name<D> {
pub fn try_new(policies: Vec<Arc<dyn $policy<D>>>) -> Result<Self, EmptyPoliciesError> {
if policies.is_empty() {
Err(EmptyPoliciesError(concat!(
stringify!($name),
" requires at least one policy"
)))
} else {
Ok(Self {
name: Cow::Borrowed(stringify!($name)),
policies,
})
}
}
}
named!($name, $credit);
};
}
constructor!(
AndPolicy,
Policy,
"A conjunction decides a grant as a whole, so this is the name \
[`crate::AccessEvaluation::granted_policy_type`] reports; name it after the rule it expresses."
);
constructor!(
OrPolicy,
Policy,
"A disjunction grants through one child, which is what \
[`crate::AccessEvaluation::granted_policy_type`] reports; this name appears in \
[`crate::AccessEvaluation::grant_path`]."
);
async fn grant_children<D: PolicyDomain>(
name: Cow<'static, str>,
policies: &[Arc<dyn Policy<D>>],
ctx: &BatchEvalCtx<'_, D>,
conjunction: bool,
single: bool,
) -> Vec<GrantResult> {
let mut children = vec![Vec::new(); ctx.items.len()];
let mut pending: Vec<usize> = (0..ctx.items.len()).collect();
for policy in policies {
let items: Vec<_> = pending
.iter()
.map(|&index| PolicyBatchItem {
resource: ctx.items[index].resource,
})
.collect();
let results = if single {
let inner = EvalCtx::new(
ctx.session(),
ctx.subject,
ctx.action,
items[0].resource,
ctx.context,
policy.policy_type(),
);
let result = policy.evaluate(&inner).await;
vec![inner.finish(result)]
} else {
let inner = BatchEvalCtx::new(
ctx.session(),
ctx.subject,
ctx.action,
ctx.context,
&items,
policy.policy_type(),
);
let results = policy.evaluate_batch(&inner).await;
inner.finish(results)
};
let results = if results.len() == pending.len() {
results
} else {
pending
.iter()
.map(|_| {
GrantResult::indeterminate(
policy.policy_type(),
"Policy batch result count did not match input count",
)
})
.collect()
};
for (&index, result) in pending.iter().zip(results) {
children[index].push(result);
}
pending.retain(|&index| {
let decision = children[index].last().expect("evaluated child").decision();
if conjunction {
decision != Decision::NotApplicable
} else {
decision != Decision::Grant
}
});
if pending.is_empty() {
break;
}
}
children
.into_iter()
.map(|children| {
if conjunction {
GrantResult::all(name.clone(), children)
} else {
GrantResult::any(name.clone(), children)
}
})
.collect()
}
macro_rules! grant_combinator {
($name:ident,$conjunction:expr) => {
#[async_trait]
impl<D: PolicyDomain> Policy<D> for $name<D> {
async fn evaluate(&self, ctx: &EvalCtx<'_, D>) -> GrantResult {
let items = [PolicyBatchItem {
resource: ctx.resource,
}];
let inner = BatchEvalCtx::new(
ctx.session(),
ctx.subject,
ctx.action,
ctx.context,
&items,
self.policy_type(),
);
grant_children(
self.name.clone(),
&self.policies,
&inner,
$conjunction,
true,
)
.await
.remove(0)
}
async fn evaluate_batch<'item>(
&self,
ctx: &BatchEvalCtx<'item, D>,
) -> Vec<GrantResult> {
if ctx.items.is_empty() {
return Vec::new();
}
grant_children(self.name.clone(), &self.policies, ctx, $conjunction, false).await
}
fn policy_type(&self) -> Cow<'static, str> {
self.name.clone()
}
}
};
}
grant_combinator!(AndPolicy, true);
grant_combinator!(OrPolicy, false);
fn invert(name: Cow<'static, str>, result: GrantResult) -> GrantResult {
let decision = match result.decision() {
Decision::Grant => Decision::NotApplicable,
Decision::NotApplicable => Decision::Grant,
_ => Decision::Indeterminate,
};
GrantResult(combined(name, CombineOp::Not, vec![result.0], decision))
}
#[async_trait]
impl<D: PolicyDomain> Policy<D> for NotPolicy<D> {
async fn evaluate(&self, ctx: &EvalCtx<'_, D>) -> GrantResult {
let inner = EvalCtx::new(
ctx.session(),
ctx.subject,
ctx.action,
ctx.resource,
ctx.context,
self.policy.policy_type(),
);
let result = self.policy.evaluate(&inner).await;
invert(self.name.clone(), inner.finish(result))
}
async fn evaluate_batch<'item>(&self, ctx: &BatchEvalCtx<'item, D>) -> Vec<GrantResult> {
let inner = BatchEvalCtx::new(
ctx.session(),
ctx.subject,
ctx.action,
ctx.context,
ctx.items,
self.policy.policy_type(),
);
let results = self.policy.evaluate_batch(&inner).await;
let results = inner.finish(results);
if results.len() != ctx.items.len() {
return ctx
.items
.iter()
.map(|_| {
GrantResult::indeterminate(
self.policy.policy_type(),
"Policy batch result count did not match input count",
)
})
.collect();
}
results
.into_iter()
.map(|result| invert(self.name.clone(), result))
.collect()
}
fn policy_type(&self) -> Cow<'static, str> {
self.name.clone()
}
}
pub trait VetoPolicyExt<D: PolicyDomain>: VetoPolicy<D> + Sized + 'static {
fn all_of<P: VetoPolicy<D> + 'static>(self, other: P) -> AllOfVeto<D> {
AllOfVeto {
name: Cow::Borrowed("AllOfVeto"),
policies: vec![Arc::new(self), Arc::new(other)],
}
}
fn any_of<P: VetoPolicy<D> + 'static>(self, other: P) -> AnyOfVeto<D> {
AnyOfVeto {
name: Cow::Borrowed("AnyOfVeto"),
policies: vec![Arc::new(self), Arc::new(other)],
}
}
fn boxed(self) -> Box<dyn VetoPolicy<D>> {
Box::new(self)
}
}
impl<D: PolicyDomain, P: VetoPolicy<D> + Sized + 'static> VetoPolicyExt<D> for P {}
pub struct AllOfVeto<D: PolicyDomain> {
name: Cow<'static, str>,
policies: Vec<Arc<dyn VetoPolicy<D>>>,
}
pub struct AnyOfVeto<D: PolicyDomain> {
name: Cow<'static, str>,
policies: Vec<Arc<dyn VetoPolicy<D>>>,
}
constructor!(
AllOfVeto,
VetoPolicy,
"An all-of veto forbids only when every child does, so this is the name \
[`crate::AccessEvaluation::forbidden_by`] reports; name it after the rule it expresses."
);
constructor!(
AnyOfVeto,
VetoPolicy,
"An any-of veto forbids through one child, which is what \
[`crate::AccessEvaluation::forbidden_by`] reports; this name appears in \
[`crate::AccessEvaluation::forbidden_path`]."
);
async fn veto_children<D: PolicyDomain>(
name: Cow<'static, str>,
policies: &[Arc<dyn VetoPolicy<D>>],
ctx: &BatchEvalCtx<'_, D>,
conjunction: bool,
single: bool,
) -> Vec<VetoResult> {
let mut children = vec![Vec::new(); ctx.items.len()];
let mut pending: Vec<usize> = (0..ctx.items.len()).collect();
for policy in policies {
let items: Vec<_> = pending
.iter()
.map(|&index| PolicyBatchItem {
resource: ctx.items[index].resource,
})
.collect();
let results = if single {
let inner = EvalCtx::new(
ctx.session(),
ctx.subject,
ctx.action,
items[0].resource,
ctx.context,
policy.policy_type(),
);
let result = policy.evaluate(&inner).await;
vec![inner.finish(result)]
} else {
let inner = BatchEvalCtx::new(
ctx.session(),
ctx.subject,
ctx.action,
ctx.context,
&items,
policy.policy_type(),
);
let results = policy.evaluate_batch(&inner).await;
inner.finish(results)
};
let results = if results.len() == pending.len() {
results
} else {
pending
.iter()
.map(|_| {
VetoResult::indeterminate(
policy.policy_type(),
"Policy batch result count did not match input count",
)
})
.collect()
};
for (&index, result) in pending.iter().zip(results) {
children[index].push(result);
}
pending.retain(|&index| {
let decision = children[index].last().expect("evaluated child").decision();
if conjunction {
decision != Decision::NotApplicable
} else {
decision != Decision::Forbid
}
});
if pending.is_empty() {
break;
}
}
children
.into_iter()
.map(|children| {
let any_forbid = children.iter().any(VetoResult::is_forbidden);
let any_pass = children
.iter()
.any(|child| child.decision() == Decision::NotApplicable);
let any_unknown = children
.iter()
.any(|child| child.decision() == Decision::Indeterminate);
let decision = if conjunction && any_pass {
Decision::NotApplicable
} else if !conjunction && any_forbid {
Decision::Forbid
} else if any_unknown {
Decision::Indeterminate
} else if conjunction && !children.is_empty() {
Decision::Forbid
} else {
Decision::NotApplicable
};
VetoResult(combined(
name.clone(),
if conjunction {
CombineOp::And
} else {
CombineOp::Or
},
children.into_iter().map(|child| child.0).collect(),
decision,
))
})
.collect()
}
macro_rules! veto_combinator {
($name:ident,$conjunction:expr) => {
#[async_trait]
impl<D: PolicyDomain> VetoPolicy<D> for $name<D> {
async fn evaluate(&self, ctx: &EvalCtx<'_, D>) -> VetoResult {
let items = [PolicyBatchItem {
resource: ctx.resource,
}];
let inner = BatchEvalCtx::new(
ctx.session(),
ctx.subject,
ctx.action,
ctx.context,
&items,
self.policy_type(),
);
veto_children(
self.name.clone(),
&self.policies,
&inner,
$conjunction,
true,
)
.await
.remove(0)
}
async fn evaluate_batch<'item>(&self, ctx: &BatchEvalCtx<'item, D>) -> Vec<VetoResult> {
if ctx.items.is_empty() {
return Vec::new();
}
veto_children(self.name.clone(), &self.policies, ctx, $conjunction, false).await
}
fn policy_type(&self) -> Cow<'static, str> {
self.name.clone()
}
}
};
}
veto_combinator!(AllOfVeto, true);
veto_combinator!(AnyOfVeto, false);