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};
pub trait PolicyDomain: Send + Sync + 'static {
type Subject: Send + Sync;
type Action: Send + Sync;
type Resource: Send + Sync;
type Context: Send + Sync;
}
pub struct PolicyBatchItem<'a, D: PolicyDomain> {
pub resource: &'a D::Resource,
}
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)
}
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()
}
pub struct EvalCtx<'a, D: PolicyDomain> {
session: &'a EvaluationSession,
pub subject: &'a D::Subject,
pub action: &'a D::Action,
pub resource: &'a D::Resource,
pub context: &'a D::Context,
pub policy_type: Cow<'static, str>,
recorded: Mutex<Vec<FactProvenance>>,
}
impl<'a, D: PolicyDomain> EvalCtx<'a, D> {
#[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()),
}
}
pub fn session(&self) -> &'a EvaluationSession {
self.session
}
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
}
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
}
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"))
}
#[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)
}
pub fn grant(&self, reason: impl Into<String>) -> GrantResult {
GrantResult(attach_recorded(
PolicyEvalResult::granted(self.policy_type.clone(), Some(reason.into())),
self.take_recorded(),
))
}
pub fn not_applicable(&self, reason: impl Into<String>) -> GrantResult {
GrantResult(attach_recorded(
PolicyEvalResult::not_applicable(self.policy_type.clone(), reason),
self.take_recorded(),
))
}
pub fn forbid(&self, reason: impl Into<String>) -> VetoResult {
VetoResult(attach_recorded(
PolicyEvalResult::forbidden(self.policy_type.clone(), reason),
self.take_recorded(),
))
}
pub fn indeterminate(&self, reason: impl Into<String>) -> GrantResult {
GrantResult(attach_recorded(
PolicyEvalResult::indeterminate(self.policy_type.clone(), reason),
self.take_recorded(),
))
}
pub fn pass(&self, reason: impl Into<String>) -> VetoResult {
VetoResult(attach_recorded(
PolicyEvalResult::not_applicable(self.policy_type.clone(), reason),
self.take_recorded(),
))
}
pub fn veto_indeterminate(&self, reason: impl Into<String>) -> VetoResult {
VetoResult(attach_recorded(
PolicyEvalResult::indeterminate(self.policy_type.clone(), reason),
self.take_recorded(),
))
}
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(),
))
}
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(),
))
}
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(),
))
}
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(),
))
}
}
pub struct BatchEvalCtx<'a, D: PolicyDomain> {
session: &'a EvaluationSession,
pub subject: &'a D::Subject,
pub action: &'a D::Action,
pub context: &'a D::Context,
pub items: &'a [PolicyBatchItem<'a, D>],
pub policy_type: Cow<'static, str>,
recorded: Mutex<Vec<Vec<FactProvenance>>>,
}
impl<'a, D: PolicyDomain> BatchEvalCtx<'a, D> {
#[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()),
}
}
pub fn session(&self) -> &'a EvaluationSession {
self.session
}
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
}
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
}
#[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()
}
}
#[async_trait]
pub trait Policy<D: PolicyDomain>: Send + Sync {
async fn evaluate(&self, ctx: &EvalCtx<'_, D>) -> GrantResult;
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
}
fn policy_type(&self) -> Cow<'static, str>;
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()
}
}