use crate::{Context, FailPolicy, GuardError, Verdict};
use std::time::Duration;
pub trait Guard: Send + Sync + std::panic::RefUnwindSafe {
type Input: ?Sized;
type Output;
fn check(
&self,
input: &Self::Input,
ctx: &Context,
) -> Result<Verdict<Self::Output>, GuardError>;
fn fail_policy(&self) -> FailPolicy {
FailPolicy::FailClosed
}
fn timeout(&self) -> Option<Duration> {
None
}
fn strict(&self) -> bool {
false
}
fn name(&self) -> &'static str;
}
#[cfg(test)]
mod tests {
use super::*;
use crate::Deadline;
use std::panic::RefUnwindSafe;
struct AlwaysAllow;
impl Guard for AlwaysAllow {
type Input = str;
type Output = ();
fn check(&self, _input: &str, _ctx: &Context) -> Result<Verdict, GuardError> {
Ok(Verdict::Allow)
}
fn name(&self) -> &'static str {
"always_allow"
}
}
struct Fussy;
impl Guard for Fussy {
type Input = String;
type Output = String;
fn check(&self, input: &String, ctx: &Context) -> Result<Verdict<String>, GuardError> {
if ctx.is_expired() {
return Err(GuardError::DeadlineViolated);
}
if input.contains("secret") {
return Ok(Verdict::Modify(input.replace("secret", "[redacted]")));
}
Ok(Verdict::Allow)
}
fn fail_policy(&self) -> FailPolicy {
FailPolicy::FailOpen
}
fn timeout(&self) -> Option<Duration> {
Some(Duration::from_millis(5))
}
fn strict(&self) -> bool {
true
}
fn name(&self) -> &'static str {
"fussy"
}
}
#[test]
fn defaults_are_fail_closed_untimed_and_non_strict() {
let guard = AlwaysAllow;
assert_eq!(guard.fail_policy(), FailPolicy::FailClosed);
assert_eq!(guard.timeout(), None);
assert!(!guard.strict());
assert_eq!(guard.name(), "always_allow");
}
#[test]
fn every_default_can_be_overridden() {
let guard = Fussy;
assert_eq!(guard.fail_policy(), FailPolicy::FailOpen);
assert_eq!(guard.timeout(), Some(Duration::from_millis(5)));
assert!(guard.strict());
}
#[test]
fn check_returns_decisions_and_failures_distinctly() {
let guard = Fussy;
let ctx = Context::new();
let allowed = guard.check(&"nothing to see".to_owned(), &ctx);
assert_eq!(allowed, Ok(Verdict::Allow));
let modified = guard.check(&"a secret value".to_owned(), &ctx);
assert_eq!(
modified,
Ok(Verdict::Modify("a [redacted] value".to_owned()))
);
let expired = Context::new().with_deadline(Deadline::after(Duration::ZERO));
let failed = guard.check(&"anything".to_owned(), &expired);
assert_eq!(failed, Err(GuardError::DeadlineViolated));
}
#[test]
fn guards_are_object_safe_and_shareable_across_threads() {
fn assert_bounds<G: Send + Sync + RefUnwindSafe + ?Sized>() {}
assert_bounds::<AlwaysAllow>();
assert_bounds::<dyn Guard<Input = str, Output = ()>>();
let guards: Vec<Box<dyn Guard<Input = str, Output = ()>>> = vec![Box::new(AlwaysAllow)];
assert_eq!(guards[0].name(), "always_allow");
}
}