use std::any::type_name;
use id_effect::Exit;
use crate::audit::{AuthzEvents, DecisionEvent, MemorySink, audited};
use crate::policy::{Decision, Denial, Policy, PolicyEffect};
use crate::principal::CurrentPrincipal;
use crate::registry::Policies;
#[derive(Clone, Debug, Default)]
pub struct AuthzTest {
policies: Policies,
sink: MemorySink,
}
impl AuthzTest {
pub fn new() -> Self {
Self::default()
}
pub fn with_policies(policies: Policies) -> Self {
let sink = MemorySink::new();
let mine = AuthzEvents::new(sink.clone());
let events = match policies.events() {
Some(existing) => existing.clone().and(mine),
None => mine,
};
Self {
policies: policies.with_events(events),
sink,
}
}
pub fn policies(&self) -> &Policies {
&self.policies
}
pub fn sink(&self) -> AuthzEvents {
AuthzEvents::new(self.sink.clone())
}
pub fn events(&self) -> Vec<DecisionEvent> {
self.sink.events()
}
pub fn take_events(&self) -> Vec<DecisionEvent> {
self.sink.take()
}
#[track_caller]
pub fn decide<Res, P>(&self, principal: &CurrentPrincipal, policy: &P, resource: &Res) -> Decision
where
Res: ?Sized,
P: Policy<Res> + ?Sized,
{
let name = type_name::<P>();
let effect = audited(
policy.evaluate(principal, resource),
&self.sink(),
principal,
name,
type_name::<Res>(),
);
run(effect, principal, name)
}
#[track_caller]
pub fn decide_named<Res: ?Sized + 'static>(
&self,
principal: &CurrentPrincipal,
name: &str,
resource: &Res,
) -> Decision {
run(
self.policies.evaluate(name, principal, resource),
principal,
name,
)
}
#[track_caller]
pub fn assert_allows<Res, P>(&self, principal: &CurrentPrincipal, policy: &P, resource: &Res)
where
Res: ?Sized,
P: Policy<Res> + ?Sized,
{
expect_allow(
self.decide(principal, policy, resource),
principal,
type_name::<P>(),
);
}
#[track_caller]
pub fn assert_denies<Res, P>(
&self,
principal: &CurrentPrincipal,
policy: &P,
resource: &Res,
) -> Denial
where
Res: ?Sized,
P: Policy<Res> + ?Sized,
{
expect_deny(
self.decide(principal, policy, resource),
principal,
type_name::<P>(),
)
}
#[track_caller]
pub fn assert_denied_because<Res, P>(
&self,
principal: &CurrentPrincipal,
policy: &P,
resource: &Res,
reason: &str,
) where
Res: ?Sized,
P: Policy<Res> + ?Sized,
{
expect_reason(&self.assert_denies(principal, policy, resource), reason);
}
#[track_caller]
pub fn assert_allows_named<Res: ?Sized + 'static>(
&self,
principal: &CurrentPrincipal,
name: &str,
resource: &Res,
) {
expect_allow(
self.decide_named(principal, name, resource),
principal,
name,
);
}
#[track_caller]
pub fn assert_denies_named<Res: ?Sized + 'static>(
&self,
principal: &CurrentPrincipal,
name: &str,
resource: &Res,
) -> Denial {
expect_deny(
self.decide_named(principal, name, resource),
principal,
name,
)
}
#[track_caller]
pub fn assert_denied_because_named<Res: ?Sized + 'static>(
&self,
principal: &CurrentPrincipal,
name: &str,
resource: &Res,
reason: &str,
) {
expect_reason(&self.assert_denies_named(principal, name, resource), reason);
}
}
#[track_caller]
fn run(effect: PolicyEffect, principal: &CurrentPrincipal, policy: &str) -> Decision {
match effect.block_on() {
Exit::Success(decision) => decision,
Exit::Failure(cause) => panic!(
"policy `{policy}` failed for principal `{}`: {cause:?}",
principal.id()
),
}
}
#[track_caller]
fn expect_allow(decision: Decision, principal: &CurrentPrincipal, policy: &str) {
if let Decision::Deny(denial) = decision {
panic!(
"expected policy `{policy}` to allow principal `{}`, it denied: {}",
principal.id(),
denial.reason()
);
}
}
#[track_caller]
fn expect_deny(decision: Decision, principal: &CurrentPrincipal, policy: &str) -> Denial {
match decision {
Decision::Deny(denial) => denial,
Decision::Allow => panic!(
"expected policy `{policy}` to deny principal `{}`, it allowed",
principal.id()
),
}
}
#[track_caller]
fn expect_reason(denial: &Denial, reason: &str) {
assert_eq!(
denial.reason(),
reason,
"the policy denied for another reason"
);
}
#[cfg(test)]
mod tests {
use super::*;
use crate::audit::{MemorySink, Outcome};
use crate::policy::{allow_all, deny_all, require_role};
use crate::principal::BasicPrincipal;
fn carl() -> CurrentPrincipal {
CurrentPrincipal::new(BasicPrincipal::new("carl").with_role("accountant"))
}
fn harness() -> AuthzTest {
AuthzTest::with_policies(
Policies::builder()
.define::<()>("post", require_role("accountant"))
.define::<()>("close", deny_all("owners only"))
.build(),
)
}
#[test]
fn direct_assertions_record_events() {
let t = AuthzTest::new();
t.assert_allows(&carl(), &require_role("accountant"), &());
let denial = t.assert_denies(&carl(), &deny_all("nope"), &());
assert_eq!(denial.reason(), "nope");
t.assert_denied_because(&carl(), &require_role("owner"), &(), "requires role owner");
assert_eq!(t.decide(&carl(), &allow_all(), &1_u8), Decision::Allow);
let events = t.take_events();
assert_eq!(events.len(), 4);
assert_eq!(events[3].resource, "u8");
assert!(
events[0].policy.contains("RequireRole"),
"{}",
events[0].policy
);
assert!(t.events().is_empty());
}
#[test]
fn named_assertions_use_the_recording_registry() {
let t = harness();
t.assert_allows_named(&carl(), "post", &());
let denial = t.assert_denies_named(&carl(), "close", &());
assert_eq!(denial.policy(), Some("close"));
t.assert_denied_because_named(&carl(), "close", &(), "owners only");
assert!(t.policies().contains("post"));
assert_eq!(t.sink().sinks(), 1);
let outcomes: Vec<_> = t.events().iter().map(|e| e.outcome).collect();
assert_eq!(outcomes, [Outcome::Allow, Outcome::Deny, Outcome::Deny]);
}
#[test]
fn an_existing_sink_keeps_receiving() {
let theirs = MemorySink::new();
let t = AuthzTest::with_policies(
Policies::builder()
.define::<()>("open", allow_all())
.events(AuthzEvents::new(theirs.clone()))
.build(),
);
t.assert_allows_named(&carl(), "open", &());
assert_eq!((theirs.len(), t.events().len()), (1, 1));
}
#[test]
#[should_panic(expected = "to allow principal `carl`, it denied: owners only")]
fn allow_assertion_panics_on_denial() {
harness().assert_allows_named(&carl(), "close", &());
}
#[test]
#[should_panic(expected = "to deny principal `carl`, it allowed")]
fn deny_assertion_panics_on_allow() {
harness().assert_denies_named(&carl(), "post", &());
}
#[test]
#[should_panic(expected = "another reason")]
fn reason_assertion_panics_on_mismatch() {
harness().assert_denied_because_named(&carl(), "close", &(), "closed");
}
#[test]
#[should_panic(expected = "policy `missing` failed for principal `carl`")]
fn evaluation_failures_panic() {
harness().assert_allows_named(&carl(), "missing", &());
}
}