pub use action_gate_types::{ActionContext, Check, Decision, Outcome};
use std::collections::BTreeSet;
use sha2::{Digest, Sha256};
#[cfg(feature = "checks-common")]
pub mod checks;
pub mod secrets;
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum Mode {
#[default]
Open,
Closed,
}
pub mod closed {
pub const NO_CHECK_DECIDED: &str = "gate:deny:closed:no_check_decided";
pub const REQUIRED_UNREGISTERED: &str = "gate:deny:closed:required_unregistered";
pub const REQUIRED_UNDECIDED: &str = "gate:deny:closed:required_undecided";
pub const AFFIRMED: &str = "gate:allow:closed:affirmed";
}
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub struct Evaluation {
pub decision: Decision,
pub denials: Vec<Decision>,
}
pub struct Gate {
checks: Vec<Box<dyn Check>>,
mode: Mode,
required: BTreeSet<String>,
}
impl Gate {
pub fn builder() -> GateBuilder {
GateBuilder::new()
}
pub fn evaluate(&self, ctx: &ActionContext) -> Decision {
match self.mode {
Mode::Open => {
for check in &self.checks {
if let Some(decision) = check.evaluate(ctx) {
return decision;
}
}
Decision::allow()
}
Mode::Closed => self.evaluate_closed(ctx, false).decision,
}
}
pub fn evaluate_exhaustive(&self, ctx: &ActionContext) -> Evaluation {
match self.mode {
Mode::Open => {
let mut decision = None;
let mut denials = Vec::new();
for check in &self.checks {
if let Some(d) = check.evaluate(ctx) {
if d.outcome == Outcome::Deny {
denials.push(d.clone());
}
decision.get_or_insert(d);
}
}
Evaluation {
decision: decision.unwrap_or_else(Decision::allow),
denials,
}
}
Mode::Closed => self.evaluate_closed(ctx, true),
}
}
fn evaluate_closed(&self, ctx: &ActionContext, exhaustive: bool) -> Evaluation {
let missing = self.unregistered_required();
if !missing.is_empty() {
let deny = Decision::deny(
closed::REQUIRED_UNREGISTERED,
missing.into_iter().map(String::from).collect(),
)
.blocking();
return Evaluation {
decision: deny.clone(),
denials: vec![deny],
};
}
let mut denials = Vec::new();
let mut degrade = None;
let mut allowed = Vec::new();
let mut ran = Vec::new();
for check in &self.checks {
let id = check.id();
ran.push(id.to_string());
match check.evaluate(ctx) {
Some(d) if d.outcome == Outcome::Deny => denials.push(d),
Some(d) if d.outcome == Outcome::Degrade => {
degrade.get_or_insert(d);
}
Some(_) => allowed.push(id.to_string()),
None if self.required.contains(id) => denials.push(
Decision::deny(closed::REQUIRED_UNDECIDED, vec![id.to_string()]).blocking(),
),
None => {}
}
if !exhaustive && !denials.is_empty() {
break;
}
}
let decision = if let Some(first) = denials.first() {
first.clone()
} else if let Some(d) = degrade {
d
} else if !allowed.is_empty() {
Decision {
outcome: Outcome::Allow,
reason: closed::AFFIRMED.into(),
check_ids: allowed,
blocking: false,
}
} else {
let deny = Decision::deny(closed::NO_CHECK_DECIDED, ran).blocking();
denials.push(deny.clone());
deny
};
Evaluation { decision, denials }
}
pub fn check_ids(&self) -> Vec<&str> {
self.checks.iter().map(|c| c.id()).collect()
}
pub fn mode(&self) -> Mode {
self.mode
}
pub fn required_ids(&self) -> Vec<&str> {
self.required.iter().map(String::as_str).collect()
}
pub fn unregistered_required(&self) -> Vec<&str> {
self.required
.iter()
.filter(|id| !self.checks.iter().any(|c| c.id() == id.as_str()))
.map(String::as_str)
.collect()
}
pub fn config_hash(&self) -> String {
let fingerprints: Vec<String> =
self.checks.iter().map(|c| c.config_fingerprint()).collect();
let value = match self.mode {
Mode::Open => {
serde_json::to_value(&fingerprints).expect("fingerprints serialise to JSON")
}
Mode::Closed => serde_json::json!({
"checks": fingerprints,
"mode": "closed",
"required": self.required,
}),
};
sha256_hex(canonical_keysort_json::to_canonical_string(&value).as_bytes())
}
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct DenyByDefault;
impl DenyByDefault {
pub const ID: &'static str = "deny-by-default";
pub const REASON: &'static str = "gate:deny:default:no_check_decided";
}
impl Check for DenyByDefault {
fn id(&self) -> &str {
Self::ID
}
fn evaluate(&self, _ctx: &ActionContext) -> Option<Decision> {
Some(Decision::deny(Self::REASON, vec![Self::ID.into()]).blocking())
}
}
#[derive(Default)]
pub struct GateBuilder {
checks: Vec<Box<dyn Check>>,
mode: Mode,
required: BTreeSet<String>,
}
impl GateBuilder {
pub fn new() -> Self {
Self::default()
}
#[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
}
#[must_use]
pub fn closed(mut self) -> Self {
self.mode = Mode::Closed;
self
}
#[must_use]
pub fn require(mut self, id: impl Into<String>) -> Self {
self.required.insert(id.into());
self.mode = Mode::Closed;
self
}
#[must_use]
pub fn require_all(self, ids: impl IntoIterator<Item = impl Into<String>>) -> Self {
ids.into_iter().fold(self, |b, id| b.require(id))
}
pub fn build(self) -> Gate {
Gate {
checks: self.checks,
mode: self.mode,
required: self.required,
}
}
pub fn build_deny_by_default(self) -> Gate {
self.check(DenyByDefault).build()
}
}
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());
}
struct AllowOn(&'static str);
impl Check for AllowOn {
fn id(&self) -> &str {
"allow-on"
}
fn evaluate(&self, ctx: &ActionContext) -> Option<Decision> {
(ctx.action == self.0).then(Decision::allow)
}
}
#[test]
fn deny_by_default_closes_the_gate() {
let gate = Gate::builder()
.check(deny_on("a", "x"))
.check(AllowOn("read"))
.build_deny_by_default();
assert!(gate.evaluate(&ActionContext::new("read")).is_allow());
let d = gate.evaluate(&ActionContext::new("z"));
assert_eq!(d.outcome, Outcome::Deny);
assert_eq!(d.reason, DenyByDefault::REASON);
assert_eq!(d.check_ids, vec!["deny-by-default"]);
assert!(d.blocking);
assert_eq!(gate.evaluate(&ActionContext::new("x")).check_ids, vec!["a"]);
assert_eq!(gate.check_ids(), vec!["a", "allow-on", "deny-by-default"]);
}
#[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"));
}
}