pub use action_gate_types::{ActionContext, Check, Decision, Outcome};
use sha2::{Digest, Sha256};
#[cfg(feature = "checks-common")]
pub mod checks;
pub struct Gate {
checks: Vec<Box<dyn Check>>,
}
impl Gate {
pub fn builder() -> GateBuilder {
GateBuilder::new()
}
pub fn evaluate(&self, ctx: &ActionContext) -> Decision {
for check in &self.checks {
if let Some(decision) = check.evaluate(ctx) {
return decision;
}
}
Decision::allow()
}
pub fn check_ids(&self) -> Vec<&str> {
self.checks.iter().map(|c| c.id()).collect()
}
pub fn config_hash(&self) -> String {
let fingerprints: Vec<String> =
self.checks.iter().map(|c| c.config_fingerprint()).collect();
let value = serde_json::to_value(&fingerprints).expect("fingerprints serialise to JSON");
sha256_hex(canonical_keysort_json::to_canonical_string(&value).as_bytes())
}
}
#[derive(Default)]
pub struct GateBuilder {
checks: Vec<Box<dyn Check>>,
}
impl GateBuilder {
pub fn new() -> Self {
Self { checks: Vec::new() }
}
#[must_use]
pub fn check<C: Check + 'static>(mut self, check: C) -> Self {
self.checks.push(Box::new(check));
self
}
#[must_use]
pub fn check_boxed(mut self, check: Box<dyn Check>) -> Self {
self.checks.push(check);
self
}
pub fn build(self) -> Gate {
Gate {
checks: self.checks,
}
}
}
pub fn decision_to_canonical_json(decision: &Decision) -> String {
canonical_keysort_json::to_canonical_string(
&serde_json::to_value(decision).expect("decision serialises to JSON"),
)
}
pub fn sha256_hex(bytes: &[u8]) -> String {
let mut hasher = Sha256::new();
hasher.update(bytes);
format!("sha256:{}", hex::encode(hasher.finalize()))
}
#[cfg(test)]
mod tests {
use super::*;
struct DenyOn {
id: String,
action: String,
}
impl Check for DenyOn {
fn id(&self) -> &str {
&self.id
}
fn evaluate(&self, ctx: &ActionContext) -> Option<Decision> {
if ctx.action == self.action {
Some(Decision::deny(
format!("gate:deny:{}", self.id),
vec![self.id.clone()],
))
} else {
None
}
}
}
fn deny_on(id: &str, action: &str) -> DenyOn {
DenyOn {
id: id.into(),
action: action.into(),
}
}
#[test]
fn empty_gate_allows() {
let gate = Gate::builder().build();
assert!(gate.evaluate(&ActionContext::new("anything")).is_allow());
}
#[test]
fn first_matching_check_wins() {
let gate = Gate::builder()
.check(deny_on("a", "x"))
.check(deny_on("b", "x"))
.build();
let d = gate.evaluate(&ActionContext::new("x"));
assert_eq!(d.outcome, Outcome::Deny);
assert_eq!(d.check_ids, vec!["a"], "first check short-circuits");
}
#[test]
fn non_matching_checks_pass_through_to_allow() {
let gate = Gate::builder()
.check(deny_on("a", "x"))
.check(deny_on("b", "y"))
.build();
assert!(gate.evaluate(&ActionContext::new("z")).is_allow());
}
#[test]
fn config_hash_is_stable_and_order_sensitive() {
let g1 = Gate::builder()
.check(deny_on("a", "x"))
.check(deny_on("b", "y"))
.build();
let g2 = Gate::builder()
.check(deny_on("a", "x"))
.check(deny_on("b", "y"))
.build();
assert_eq!(g1.config_hash(), g2.config_hash(), "same config, same hash");
assert!(g1.config_hash().starts_with("sha256:"));
let reordered = Gate::builder()
.check(deny_on("b", "y"))
.check(deny_on("a", "x"))
.build();
assert_ne!(
g1.config_hash(),
reordered.config_hash(),
"order changes the hash"
);
}
#[test]
fn decision_canonical_json_is_byte_stable() {
let d = Decision::deny("gate:deny:x", vec!["x".into()]).blocking();
assert_eq!(
decision_to_canonical_json(&d),
decision_to_canonical_json(&d.clone())
);
assert!(decision_to_canonical_json(&d).starts_with("{\"blocking\":true"));
}
}