use crate::{FactLoadErrorKind, FactLoadResult};
use std::borrow::Cow;
use std::fmt;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
#[cfg_attr(feature = "serde", serde(rename_all = "snake_case"))]
#[non_exhaustive]
pub enum CombineOp {
And,
Or,
Not,
Delegate,
DenyOverrides,
}
impl fmt::Display for CombineOp {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
CombineOp::And => write!(f, "AND"),
CombineOp::Or => write!(f, "OR"),
CombineOp::Not => write!(f, "NOT"),
CombineOp::Delegate => write!(f, "DELEGATE"),
CombineOp::DenyOverrides => write!(f, "DENY_OVERRIDES"),
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
#[cfg_attr(feature = "serde", serde(rename_all = "snake_case"))]
#[non_exhaustive]
pub enum Decision {
Grant,
NotApplicable,
Forbid,
Indeterminate,
}
impl fmt::Display for Decision {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Grant => write!(f, "GRANT"),
Self::NotApplicable => write!(f, "NOT_APPLICABLE"),
Self::Forbid => write!(f, "FORBID"),
Self::Indeterminate => write!(f, "INDETERMINATE"),
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
#[cfg_attr(feature = "serde", serde(rename_all = "snake_case"))]
#[non_exhaustive]
pub enum FactOutcome {
Found,
Missing,
Error,
}
impl FactOutcome {
pub fn from_load_result<V>(result: &crate::FactLoadResult<V>) -> Self {
match result {
crate::FactLoadResult::Found(_) => Self::Found,
crate::FactLoadResult::Missing => Self::Missing,
crate::FactLoadResult::Error(_) => Self::Error,
}
}
}
impl fmt::Display for FactOutcome {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Found => write!(f, "found"),
Self::Missing => write!(f, "missing"),
Self::Error => write!(f, "error"),
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
pub struct FactProvenance {
pub fact_name: &'static str,
pub key: String,
pub outcome: FactOutcome,
pub detail: Option<String>,
#[cfg_attr(feature = "serde", serde(skip_serializing_if = "Option::is_none"))]
pub error_kind: Option<FactLoadErrorKind>,
}
impl FactProvenance {
pub fn new(
fact_name: &'static str,
key: impl Into<String>,
outcome: FactOutcome,
detail: Option<String>,
) -> Self {
Self {
fact_name,
key: key.into(),
outcome,
detail,
error_kind: None,
}
}
pub fn from_load_result<V>(
fact_name: &'static str,
key: impl Into<String>,
result: &FactLoadResult<V>,
) -> Self {
let (detail, error_kind) = match result {
FactLoadResult::Error(error) => (Some(error.to_string()), Some(error.kind())),
FactLoadResult::Found(_) | FactLoadResult::Missing => (None, None),
};
Self {
fact_name,
key: key.into(),
outcome: FactOutcome::from_load_result(result),
detail,
error_kind,
}
}
}
impl fmt::Display for FactProvenance {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(
f,
"fact {} [{}]: {}",
self.fact_name, self.outcome, self.key
)?;
if let Some(detail) = &self.detail {
write!(f, " ({detail})")?;
}
Ok(())
}
}
#[derive(Debug, Clone)]
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
#[cfg_attr(feature = "serde", serde(rename_all = "snake_case"))]
#[non_exhaustive]
pub enum PolicyEvalResult {
Granted {
policy_type: Cow<'static, str>,
reason: Option<String>,
provenance: Vec<FactProvenance>,
},
NotApplicable {
policy_type: Cow<'static, str>,
reason: String,
provenance: Vec<FactProvenance>,
},
Forbidden {
policy_type: Cow<'static, str>,
reason: String,
provenance: Vec<FactProvenance>,
},
Indeterminate {
policy_type: Cow<'static, str>,
reason: String,
provenance: Vec<FactProvenance>,
},
Combined {
policy_type: Cow<'static, str>,
operation: CombineOp,
children: Vec<PolicyEvalResult>,
decision: Decision,
provenance: Vec<FactProvenance>,
},
}
#[derive(Debug, Clone)]
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
#[cfg_attr(feature = "serde", serde(rename_all = "snake_case"))]
#[non_exhaustive]
#[must_use = "inspect the authorization decision or propagate it with into_result()?"]
pub enum AccessEvaluation {
Granted {
policy_type: Cow<'static, str>,
reason: Option<String>,
trace: EvalTrace,
},
Denied {
trace: EvalTrace,
reason: String,
},
Indeterminate {
trace: EvalTrace,
reason: String,
},
}
#[derive(Debug, Clone)]
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
#[non_exhaustive]
pub enum AccessError {
Denied {
reason: String,
trace: EvalTrace,
},
Indeterminate {
reason: String,
trace: EvalTrace,
},
}
impl AccessError {
pub fn trace(&self) -> &EvalTrace {
match self {
Self::Denied { trace, .. } | Self::Indeterminate { trace, .. } => trace,
}
}
pub fn fact_load_errors(&self) -> Vec<&FactProvenance> {
let mut errors = Vec::new();
if let Some(root) = self.trace().root() {
collect_fact_load_errors(root, &mut errors);
}
errors
}
}
impl fmt::Display for AccessError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Denied { reason, .. } => write!(f, "access denied: {reason}"),
Self::Indeterminate { reason, .. } => {
write!(f, "authorization indeterminate: {reason}")
}
}
}
}
impl std::error::Error for AccessError {}
pub struct FilterError<T> {
pub evaluations: Vec<(T, AccessEvaluation)>,
}
impl<T> fmt::Debug for FilterError<T> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_map()
.entries(
self.evaluations
.iter()
.enumerate()
.map(|(index, (_, evaluation))| (index, evaluation)),
)
.finish()
}
}
impl<T> FilterError<T> {
pub fn indeterminate(&self) -> impl Iterator<Item = (&T, &AccessEvaluation)> {
self.evaluations
.iter()
.filter(|(_, evaluation)| evaluation.is_indeterminate())
.map(|(item, evaluation)| (item, evaluation))
}
}
impl<T> fmt::Display for FilterError<T> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str("could not determine authorization for every item")
}
}
impl<T> std::error::Error for FilterError<T> {}
fn leaf_not_applicable_matches(node: &PolicyEvalResult, expected: &str) -> bool {
match node {
PolicyEvalResult::NotApplicable { policy_type, .. } => policy_type.as_ref() == expected,
PolicyEvalResult::Granted { .. }
| PolicyEvalResult::Forbidden { .. }
| PolicyEvalResult::Indeterminate { .. } => false,
PolicyEvalResult::Combined { children, .. } => children
.iter()
.any(|child| leaf_not_applicable_matches(child, expected)),
}
}
fn collect_fact_load_errors<'a>(node: &'a PolicyEvalResult, out: &mut Vec<&'a FactProvenance>) {
out.extend(
node.provenance()
.iter()
.filter(|fact| fact.outcome == FactOutcome::Error),
);
if let PolicyEvalResult::Combined { children, .. } = node {
for child in children {
collect_fact_load_errors(child, out);
}
}
}
fn trace_has_fact_load_error(node: &PolicyEvalResult) -> bool {
node.provenance()
.iter()
.any(|fact| fact.outcome == FactOutcome::Error)
|| matches!(node, PolicyEvalResult::Combined { children, .. } if children.iter().any(trace_has_fact_load_error))
}
impl AccessEvaluation {
pub fn is_granted(&self) -> bool {
matches!(self, Self::Granted { .. })
}
pub fn is_indeterminate(&self) -> bool {
matches!(self, Self::Indeterminate { .. })
}
pub fn trace(&self) -> &EvalTrace {
match self {
Self::Granted { trace, .. }
| Self::Denied { trace, .. }
| Self::Indeterminate { trace, .. } => trace,
}
}
pub fn granted_policy_type(&self) -> Option<&str> {
match self {
Self::Granted { policy_type, .. } => Some(policy_type),
Self::Denied { .. } | Self::Indeterminate { .. } => None,
}
}
pub fn denied_reason(&self) -> Option<&str> {
match self {
Self::Denied { reason, .. } => Some(reason),
Self::Granted { .. } | Self::Indeterminate { .. } => None,
}
}
pub fn indeterminate_reason(&self) -> Option<&str> {
match self {
Self::Indeterminate { reason, .. } => Some(reason),
Self::Granted { .. } | Self::Denied { .. } => None,
}
}
pub fn forbidden_by(&self) -> Option<&str> {
let Self::Denied { trace, .. } = self else {
return None;
};
let Some(PolicyEvalResult::Combined {
operation: CombineOp::DenyOverrides,
children,
..
}) = trace.root()
else {
return None;
};
children
.iter()
.find_map(|child| child.forbidden_leaf().map(|(policy_type, _)| policy_type))
}
pub fn fact_load_errors(&self) -> Vec<&FactProvenance> {
let mut errors = Vec::new();
if let Some(root) = self.trace().root() {
collect_fact_load_errors(root, &mut errors);
}
errors
}
#[deprecated(
since = "0.6.0",
note = "use is_indeterminate() for the structural signal, or fact_load_errors() to inspect failed loads; this any-error-in-trace scan will be removed in 0.7"
)]
pub fn denied_due_to_fact_load_error(&self) -> bool {
match self {
Self::Denied { trace, .. } | Self::Indeterminate { trace, .. } => {
trace.root().is_some_and(trace_has_fact_load_error)
}
Self::Granted { .. } => false,
}
}
#[track_caller]
pub fn assert_granted_by(&self, expected: &str) {
match self {
Self::Granted { policy_type, .. } => {
assert_eq!(
policy_type.as_ref(),
expected,
"expected grant by policy `{expected}`, but the grant came from `{policy_type}`"
);
}
Self::Denied { reason, .. } => {
panic!("expected grant by policy `{expected}`, but access was denied: {reason}");
}
Self::Indeterminate { reason, .. } => {
panic!(
"expected grant by policy `{expected}`, but the evaluation was \
indeterminate: {reason}"
);
}
}
}
#[track_caller]
pub fn assert_denied(&self) {
match self {
Self::Denied { .. } => {}
Self::Granted {
policy_type,
reason,
..
} => {
panic!(
"expected denial, but access was granted by `{policy_type}`{}",
reason
.as_ref()
.map(|r| format!(": {r}"))
.unwrap_or_default()
);
}
Self::Indeterminate { reason, .. } => {
panic!("expected denial, but the evaluation was indeterminate: {reason}");
}
}
}
#[track_caller]
pub fn assert_indeterminate(&self) {
match self {
Self::Indeterminate { .. } => {}
Self::Granted { policy_type, .. } => {
panic!(
"expected an indeterminate evaluation, but access was granted by \
`{policy_type}`"
);
}
Self::Denied { reason, .. } => {
panic!("expected an indeterminate evaluation, but access was denied: {reason}");
}
}
}
#[track_caller]
pub fn assert_denied_with_reason_containing(&self, needle: &str) {
match self {
Self::Denied { reason, .. } => {
assert!(
reason.contains(needle),
"expected summary denial reason to contain `{needle}`, got `{reason}`"
);
}
Self::Granted { policy_type, .. } => {
panic!(
"expected denial containing `{needle}`, but access was granted by `{policy_type}`"
);
}
Self::Indeterminate { reason, .. } => {
panic!(
"expected denial containing `{needle}`, but the evaluation was \
indeterminate: {reason}"
);
}
}
}
#[track_caller]
pub fn assert_not_applicable_by(&self, expected: &str) {
match self {
Self::Granted { policy_type, .. } => {
panic!(
"expected not-applicable by policy `{expected}`, but access was granted by `{policy_type}`"
);
}
Self::Indeterminate { reason, .. } => {
panic!(
"expected not-applicable by policy `{expected}`, but the evaluation was \
indeterminate: {reason}"
);
}
Self::Denied { trace, .. } => {
let Some(root) = trace.root() else {
panic!("expected not-applicable by `{expected}`, but the trace is empty");
};
if !leaf_not_applicable_matches(root, expected) {
panic!(
"expected a not-applicable leaf for policy `{expected}` in the trace; \
got:\n{}",
trace.format()
);
}
}
}
}
#[track_caller]
pub fn assert_forbidden_by(&self, expected: &str) {
match self {
Self::Granted { policy_type, .. } => {
panic!(
"expected forbid by policy `{expected}`, but access was granted by `{policy_type}`"
);
}
Self::Indeterminate { reason, .. } => {
panic!(
"expected forbid by policy `{expected}`, but the evaluation was \
indeterminate: {reason}"
);
}
Self::Denied { .. } => match self.forbidden_by() {
Some(actual) => assert_eq!(
actual, expected,
"expected forbid by policy `{expected}`, but the forbid came from `{actual}`"
),
None => panic!(
"expected forbid by policy `{expected}`, but the denial was not a forbid; \
got:\n{}",
self.display_trace()
),
},
}
}
#[track_caller]
pub fn assert_trace_contains(&self, needle: &str) {
let rendered = self.display_trace();
assert!(
rendered.contains(needle),
"expected evaluation trace to contain `{needle}`; got:\n{rendered}"
);
}
pub fn to_result<E>(&self, error_fn: impl FnOnce(&str) -> E) -> Result<(), E> {
match self {
Self::Granted { .. } => Ok(()),
Self::Denied { reason, .. } | Self::Indeterminate { reason, .. } => {
Err(error_fn(reason))
}
}
}
pub fn into_result(self) -> Result<(), AccessError> {
match self {
Self::Granted { .. } => Ok(()),
Self::Denied { reason, trace } => Err(AccessError::Denied { reason, trace }),
Self::Indeterminate { reason, trace } => {
Err(AccessError::Indeterminate { reason, trace })
}
}
}
pub fn display_trace(&self) -> String {
let trace_str = self.trace().format();
if trace_str == "No evaluation trace available" {
format!("{}\n(No evaluation trace available)", self)
} else {
format!("{}\nEvaluation Trace:\n{}", self, trace_str)
}
}
}
impl fmt::Display for AccessEvaluation {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Granted {
policy_type,
reason,
trace: _,
} => {
match reason {
Some(r) => write!(f, "[GRANTED] by {} - {}", policy_type, r),
None => write!(f, "[GRANTED] by {}", policy_type),
}
}
Self::Denied { reason, trace: _ } => {
write!(f, "[Denied] - {}", reason)
}
Self::Indeterminate { reason, trace: _ } => {
write!(f, "[INDETERMINATE] - {}", reason)
}
}
}
}
#[derive(Debug, Clone, Default)]
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
pub struct EvalTrace {
root: Option<PolicyEvalResult>,
}
impl EvalTrace {
pub fn new() -> Self {
Self { root: None }
}
pub fn with_root(result: PolicyEvalResult) -> Self {
Self { root: Some(result) }
}
pub fn set_root(&mut self, result: PolicyEvalResult) {
self.root = Some(result);
}
pub fn root(&self) -> Option<&PolicyEvalResult> {
self.root.as_ref()
}
pub fn format(&self) -> String {
match &self.root {
Some(root) => root.format(0),
None => "No evaluation trace available".to_string(),
}
}
}
impl PolicyEvalResult {
pub fn granted(policy_type: impl Into<Cow<'static, str>>, reason: Option<String>) -> Self {
Self::Granted {
policy_type: policy_type.into(),
reason,
provenance: Vec::new(),
}
}
pub fn not_applicable(
policy_type: impl Into<Cow<'static, str>>,
reason: impl Into<String>,
) -> Self {
Self::NotApplicable {
policy_type: policy_type.into(),
reason: reason.into(),
provenance: Vec::new(),
}
}
pub fn forbidden(policy_type: impl Into<Cow<'static, str>>, reason: impl Into<String>) -> Self {
Self::Forbidden {
policy_type: policy_type.into(),
reason: reason.into(),
provenance: Vec::new(),
}
}
pub fn granted_with_facts(
policy_type: impl Into<Cow<'static, str>>,
reason: Option<String>,
provenance: Vec<FactProvenance>,
) -> Self {
Self::Granted {
policy_type: policy_type.into(),
reason,
provenance,
}
}
pub fn not_applicable_with_facts(
policy_type: impl Into<Cow<'static, str>>,
reason: impl Into<String>,
provenance: Vec<FactProvenance>,
) -> Self {
crate::policy::attach_recorded(Self::not_applicable(policy_type, reason), provenance)
}
pub fn forbidden_with_facts(
policy_type: impl Into<Cow<'static, str>>,
reason: impl Into<String>,
provenance: Vec<FactProvenance>,
) -> Self {
Self::Forbidden {
policy_type: policy_type.into(),
reason: reason.into(),
provenance,
}
}
pub fn indeterminate(
policy_type: impl Into<Cow<'static, str>>,
reason: impl Into<String>,
) -> Self {
Self::Indeterminate {
policy_type: policy_type.into(),
reason: reason.into(),
provenance: Vec::new(),
}
}
pub fn indeterminate_with_facts(
policy_type: impl Into<Cow<'static, str>>,
reason: impl Into<String>,
provenance: Vec<FactProvenance>,
) -> Self {
Self::Indeterminate {
policy_type: policy_type.into(),
reason: reason.into(),
provenance,
}
}
pub fn policy_type(&self) -> &str {
match self {
Self::Granted { policy_type, .. }
| Self::NotApplicable { policy_type, .. }
| Self::Forbidden { policy_type, .. }
| Self::Indeterminate { policy_type, .. }
| Self::Combined { policy_type, .. } => policy_type,
}
}
pub fn decision(&self) -> Decision {
match self {
Self::Granted { .. } => Decision::Grant,
Self::NotApplicable { .. } => Decision::NotApplicable,
Self::Forbidden { .. } => Decision::Forbid,
Self::Indeterminate { .. } => Decision::Indeterminate,
Self::Combined { decision, .. } => *decision,
}
}
pub fn is_granted(&self) -> bool {
self.decision() == Decision::Grant
}
pub fn is_forbidden(&self) -> bool {
self.decision() == Decision::Forbid
}
pub(crate) fn forbidden_leaf(&self) -> Option<(&str, Option<&str>)> {
match self {
Self::Forbidden {
policy_type,
reason,
..
} => Some((policy_type.as_ref(), Some(reason.as_str()))),
Self::Combined {
children,
decision: Decision::Forbid,
..
} => children.iter().find_map(Self::forbidden_leaf),
Self::Combined { .. } => None,
Self::Granted { .. } | Self::NotApplicable { .. } | Self::Indeterminate { .. } => None,
}
}
pub(crate) fn indeterminate_leaf(&self) -> Option<(&str, &str)> {
const FACT_FAILURE_REASON: &str = "A consulted fact could not be loaded";
match self {
Self::Indeterminate {
policy_type,
reason,
..
} => Some((policy_type.as_ref(), reason.as_str())),
Self::Combined {
policy_type,
children,
provenance,
decision: Decision::Indeterminate,
..
} => children
.iter()
.find_map(Self::indeterminate_leaf)
.or_else(|| {
provenance
.iter()
.any(|fact| fact.outcome == FactOutcome::Error)
.then(|| (policy_type.as_ref(), FACT_FAILURE_REASON))
}),
Self::Combined { .. }
| Self::Granted { .. }
| Self::NotApplicable { .. }
| Self::Forbidden { .. } => None,
}
}
pub fn reason(&self) -> Option<String> {
self.reason_str().map(str::to_owned)
}
pub fn reason_str(&self) -> Option<&str> {
match self {
Self::Granted { reason, .. } => reason.as_deref(),
Self::NotApplicable { reason, .. }
| Self::Forbidden { reason, .. }
| Self::Indeterminate { reason, .. } => Some(reason),
Self::Combined { .. } => None,
}
}
pub fn provenance(&self) -> &[FactProvenance] {
match self {
Self::Granted { provenance, .. }
| Self::NotApplicable { provenance, .. }
| Self::Forbidden { provenance, .. }
| Self::Indeterminate { provenance, .. }
| Self::Combined { provenance, .. } => provenance,
}
}
pub fn format(&self, indent: usize) -> String {
let indent_str = " ".repeat(indent);
match self {
Self::Granted {
policy_type,
reason,
provenance,
} => {
let reason_text = reason
.as_ref()
.map_or("".to_string(), |r| format!(": {}", r));
let headline = format!("{}✔ {} GRANTED{}", indent_str, policy_type, reason_text);
Self::append_provenance(headline, &indent_str, provenance)
}
Self::NotApplicable {
policy_type,
reason,
provenance,
} => {
let headline =
format!("{}✘ {} NOT_APPLICABLE: {}", indent_str, policy_type, reason);
Self::append_provenance(headline, &indent_str, provenance)
}
Self::Forbidden {
policy_type,
reason,
provenance,
} => {
let headline = format!("{}⛔ {} FORBIDDEN: {}", indent_str, policy_type, reason);
Self::append_provenance(headline, &indent_str, provenance)
}
Self::Indeterminate {
policy_type,
reason,
provenance,
} => {
let headline = format!("{}⚠ {} INDETERMINATE: {}", indent_str, policy_type, reason);
Self::append_provenance(headline, &indent_str, provenance)
}
Self::Combined {
policy_type,
operation,
children,
decision,
provenance,
} => {
let decision_char = match decision {
Decision::Grant => "✔",
Decision::NotApplicable => "✘",
Decision::Forbid => "⛔",
Decision::Indeterminate => "⚠",
};
let mut result = format!(
"{}{} {} ({})",
indent_str, decision_char, policy_type, operation
);
result = Self::append_provenance(result, &indent_str, provenance);
for child in children {
result.push_str(&format!("\n{}", child.format(indent + 2)));
}
result
}
}
}
fn append_provenance(
headline: String,
indent_str: &str,
provenance: &[FactProvenance],
) -> String {
let mut result = headline;
for fact in provenance {
result.push_str(&format!("\n{indent_str} ↳ {fact}"));
}
result
}
}
impl fmt::Display for PolicyEvalResult {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let tree = self.format(0);
write!(f, "{}", tree)
}
}