warder 0.1.0

A policy gate for MCP tool calls - blocks destructive AI agent actions before they run
Documentation
//! In-process policy evaluation with Cedar.
//!
//! Cedar rather than a bespoke WASM policy engine: it is Apache-2.0, Rust-native (so
//! there is no marshalling cost across a WASM boundary), has bounded evaluation as an
//! explicit design goal, and ships symbolic verification that produces concrete
//! counterexamples. Writing our own would mean also writing a compiler, a linter, an
//! LSP, and — most importantly — a decision-explainability story, which is the single
//! most requested capability in an authorization product.
//!
//! Cedar returns Allow or Deny. The third outcome this product needs,
//! `RequireApproval`, is carried as a policy annotation (`@advice("require_approval")`)
//! on the permitting policy, which keeps the whole decision in one evaluation pass.

use cedar_policy::{
    Authorizer, Context, Entities, EntityId, EntityTypeName, EntityUid, PolicySet, Request,
};
use serde::{Deserialize, Serialize};
use serde_json::json;

use crate::preflight::{OperationClass, PreflightReport};

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum Effect {
    Allow,
    Deny,
    RequireApproval,
    /// The engine could not reach a decision. Distinguished from Deny so that an
    /// outage is never indistinguishable from a policy denial in the audit trail.
    FailClosed,
    /// Explicitly allowed *because* the engine was unavailable and the tenant has
    /// configured availability over safety. Recorded distinctly for the same reason.
    FailOpen,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Decision {
    pub effect: Effect,
    /// Policy IDs that produced this decision — the answer to "why was this blocked?".
    pub matched_policies: Vec<String>,
    pub reason: String,
}

impl Decision {
    pub fn is_blocking(&self) -> bool {
        matches!(
            self.effect,
            Effect::Deny | Effect::RequireApproval | Effect::FailClosed
        )
    }
}

pub struct PolicyEngine {
    policies: PolicySet,
    authorizer: Authorizer,
    /// When the engine cannot evaluate, deny (true) or allow (false). Per-policy in the
    /// full product; a single switch here. The local shim defaults to fail-open so a
    /// shim bug can never break a developer's session — a deliberate trade-off that is
    /// stated plainly to customers rather than emerging from buffer pressure.
    pub fail_closed: bool,
}

impl PolicyEngine {
    pub fn from_source(src: &str, fail_closed: bool) -> anyhow::Result<Self> {
        let policies: PolicySet = src
            .parse()
            .map_err(|e| anyhow::anyhow!("policy parse error: {e}"))?;
        Ok(PolicyEngine {
            policies,
            authorizer: Authorizer::new(),
            fail_closed,
        })
    }

    fn class_str(c: OperationClass) -> &'static str {
        match c {
            OperationClass::Read => "read",
            OperationClass::Write => "write",
            OperationClass::Destructive => "destructive",
            OperationClass::Unknown => "unknown",
        }
    }

    /// Evaluate one tool call. No network I/O, no allocation beyond the request context.
    pub fn evaluate(
        &self,
        agent_id: &str,
        server: &str,
        tool: &str,
        report: &PreflightReport,
    ) -> Decision {
        // Entity UIDs are built from a parsed type name plus an EntityId constructed
        // directly from the string — never by formatting a Cedar literal. A tool or
        // server name is attacker-controlled (a malicious MCP server chooses what it
        // advertises), so string interpolation into policy syntax would be an injection
        // vector. `EntityId::new` is infallible and performs no parsing, which removes
        // the vector structurally rather than by escaping.
        let principal = uid("Agent", agent_id);
        let action = uid("Action", "invoke");
        let resource = uid("Tool", &format!("{server}::{tool}"));

        let ctx_json = json!({
            "operation_class": Self::class_str(report.class),
            "signals": report.signals,
            "server": server,
            "tool": tool,
            "dry_run_available": report.dry_run_available,
        });
        let context = match Context::from_json_value(ctx_json, None) {
            Ok(c) => c,
            Err(e) => return self.unavailable(&format!("bad context: {e}")),
        };

        let request = match Request::new(principal, action, resource, context, None) {
            Ok(r) => r,
            Err(e) => return self.unavailable(&format!("bad request: {e}")),
        };

        let response = self
            .authorizer
            .is_authorized(&request, &self.policies, &Entities::empty());
        // Cedar assigns anonymous policies ids like "policy0". Prefer the author's
        // @id("...") annotation so an audit record names the rule a human wrote.
        let matched: Vec<String> = response
            .diagnostics()
            .reason()
            .map(|pid| {
                self.policies
                    .policy(pid)
                    .and_then(|p| p.annotation("id"))
                    .map(|s| s.to_string())
                    .unwrap_or_else(|| pid.to_string())
            })
            .collect();

        match response.decision() {
            cedar_policy::Decision::Allow => {
                // A permitting policy annotated @advice("require_approval") escalates
                // the allow into a human-in-the-loop gate.
                let needs_approval = response.diagnostics().reason().any(|pid| {
                    self.policies
                        .policy(pid)
                        .and_then(|p| p.annotation("advice"))
                        .map(|a| a == "require_approval")
                        .unwrap_or(false)
                });
                if needs_approval {
                    Decision {
                        effect: Effect::RequireApproval,
                        reason: format!(
                            "{} operation permitted subject to approval",
                            Self::class_str(report.class)
                        ),
                        matched_policies: matched,
                    }
                } else {
                    Decision {
                        effect: Effect::Allow,
                        reason: "permitted by policy".into(),
                        matched_policies: matched,
                    }
                }
            }
            cedar_policy::Decision::Deny => Decision {
                effect: Effect::Deny,
                reason: if matched.is_empty() {
                    // Cedar is default-deny: no permit matched at all.
                    format!(
                        "no policy permits a '{}' operation on {}::{}",
                        Self::class_str(report.class),
                        server,
                        tool
                    )
                } else {
                    format!("forbidden by policy ({})", matched.join(", "))
                },
                matched_policies: matched,
            },
        }
    }

    fn unavailable(&self, why: &str) -> Decision {
        Decision {
            effect: if self.fail_closed {
                Effect::FailClosed
            } else {
                Effect::FailOpen
            },
            matched_policies: vec![],
            reason: format!("policy engine unavailable: {why}"),
        }
    }
}

/// Build an entity UID from a fixed type name and an arbitrary id. The type names are
/// compile-time constants and always parse; the id is passed through `EntityId::new`,
/// which is infallible and does no parsing.
fn uid(type_name: &'static str, id: &str) -> EntityUid {
    let t: EntityTypeName = type_name
        .parse()
        .expect("entity type names in this module are compile-time constants");
    EntityUid::from_type_name_and_id(t, EntityId::new(id))
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::preflight::classify_sql;

    const POLICY: &str = r#"
        // Reads are always permitted.
        @id("allow-reads")
        permit(principal, action == Action::"invoke", resource)
        when { context.operation_class == "read" };

        // Bounded writes are permitted but require a human approval.
        @id("writes-need-approval")
        @advice("require_approval")
        permit(principal, action == Action::"invoke", resource)
        when { context.operation_class == "write" };

        // Destructive operations are denied outright, overriding any permit.
        @id("deny-destructive")
        forbid(principal, action, resource)
        when { context.operation_class == "destructive" };
    "#;

    fn engine() -> PolicyEngine {
        PolicyEngine::from_source(POLICY, true).expect("policy compiles")
    }

    #[test]
    fn read_is_allowed() {
        let r = classify_sql("SELECT * FROM users");
        let d = engine().evaluate("claude-code", "postgres", "execute_sql", &r);
        assert_eq!(d.effect, Effect::Allow);
        assert!(!d.is_blocking());
    }

    #[test]
    fn drop_table_is_denied() {
        let r = classify_sql("DROP TABLE users;");
        let d = engine().evaluate("claude-code", "postgres", "execute_sql", &r);
        assert_eq!(d.effect, Effect::Deny);
        assert!(d.is_blocking());
        assert!(d.matched_policies.iter().any(|p| p == "deny-destructive"));
    }

    #[test]
    fn unbounded_delete_is_denied() {
        let r = classify_sql("DELETE FROM users");
        assert_eq!(
            engine().evaluate("a", "postgres", "execute_sql", &r).effect,
            Effect::Deny
        );
    }

    #[test]
    fn bounded_update_requires_approval() {
        let r = classify_sql("UPDATE users SET name='x' WHERE id=1");
        let d = engine().evaluate("a", "postgres", "execute_sql", &r);
        assert_eq!(d.effect, Effect::RequireApproval);
        assert!(
            d.is_blocking(),
            "an approval gate must hold the call, not pass it through"
        );
    }

    #[test]
    fn unknown_statements_are_denied_by_default() {
        // Cedar is default-deny and no policy covers "unknown".
        let r = classify_sql("VACUUM FULL");
        let d = engine().evaluate("a", "postgres", "execute_sql", &r);
        assert_eq!(d.effect, Effect::Deny);
        assert!(d.matched_policies.is_empty());
        assert!(d.reason.contains("no policy permits"));
    }

    #[test]
    fn quotes_in_tool_name_cannot_forge_an_entity_uid() {
        let r = classify_sql("SELECT 1");
        // A malicious server advertising this tool name must not escape the UID literal.
        let d = engine().evaluate("a", "postgres", "x\",\n forbid(principal", &r);
        assert_eq!(
            d.effect,
            Effect::Allow,
            "a hostile tool name must be data, never policy syntax"
        );
    }

    #[test]
    fn broken_policy_source_is_rejected_at_load() {
        assert!(PolicyEngine::from_source("permit(", true).is_err());
    }
}