warder 0.1.0

A policy gate for MCP tool calls - blocks destructive AI agent actions before they run
Documentation
//! Pre-flight risk analysis.
//!
//! This module deliberately does NOT claim to predict the outcome of a remote mutation.
//! You cannot: the target system's state, business logic, triggers, webhooks and
//! concurrent writers are not observable from here. What it does is classify the
//! operation and estimate blast radius from the arguments alone, which is what actually
//! stops the "agent dropped the production table" incident.
//!
//! True dry-run — BEGIN / execute / capture rowcount / ROLLBACK — is implemented in the
//! connector layer where a database connection exists, and is only offered for tools
//! whose backend supports it. See `docs/ARCHITECTURE.md` for the caveats that must be
//! stated honestly to customers: sequences are not rolled back, triggers touching
//! external systems are not rolled back, the rollback holds locks for its duration, and
//! real execution runs against a different snapshot.

use serde::{Deserialize, Serialize};

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum OperationClass {
    /// No state change: SELECT, list, get, describe.
    Read,
    /// Bounded state change: INSERT, or UPDATE/DELETE with a predicate.
    Write,
    /// Unbounded or irreversible: DROP, TRUNCATE, ALTER, GRANT, or an
    /// UPDATE/DELETE with no WHERE clause.
    Destructive,
    /// Could not be classified — treated as Destructive by the default policy.
    Unknown,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PreflightReport {
    pub class: OperationClass,
    /// Stable, low-cardinality labels a policy can match on. Never contains values.
    pub signals: Vec<String>,
    /// True when a rollback-based dry-run is available for this tool's backend.
    pub dry_run_available: bool,
    pub rationale: String,
}

impl PreflightReport {
    pub fn unknown(reason: &str) -> Self {
        PreflightReport {
            class: OperationClass::Unknown,
            signals: vec!["unclassified".into()],
            dry_run_available: false,
            rationale: reason.into(),
        }
    }
}

/// Strip string literals, then line and block comments, so that keyword matching cannot
/// be fooled by `SELECT 'drop table users'` or by `DROP/*x*/TABLE`.
fn normalize(sql: &str) -> String {
    let mut out = String::with_capacity(sql.len());
    let b: Vec<char> = sql.chars().collect();
    let (mut i, n) = (0usize, b.len());
    let (mut in_s, mut in_d, mut in_line, mut block) = (false, false, false, 0usize);
    while i < n {
        let c = b[i];
        let next = if i + 1 < n { b[i + 1] } else { '\0' };
        if in_line {
            if c == '\n' {
                in_line = false;
                out.push(' ');
            }
            i += 1;
            continue;
        }
        if block > 0 {
            if c == '*' && next == '/' {
                block -= 1;
                i += 2;
                out.push(' ');
                continue;
            }
            if c == '/' && next == '*' {
                block += 1;
                i += 2;
                continue;
            }
            i += 1;
            continue;
        }
        if in_s {
            // '' is an escaped quote inside a single-quoted literal
            if c == '\'' && next == '\'' {
                i += 2;
                continue;
            }
            if c == '\'' {
                in_s = false;
            }
            i += 1;
            continue;
        }
        if in_d {
            if c == '"' {
                in_d = false;
            }
            i += 1;
            continue;
        }
        match (c, next) {
            ('-', '-') => {
                in_line = true;
                i += 2;
            }
            ('/', '*') => {
                block += 1;
                i += 2;
            }
            ('\'', _) => {
                in_s = true;
                out.push(' ');
                i += 1;
            }
            ('"', _) => {
                in_d = true;
                out.push(' ');
                i += 1;
            }
            _ => {
                out.push(c.to_ascii_uppercase());
                i += 1;
            }
        }
    }
    // collapse whitespace so token boundaries are predictable
    out.split_whitespace().collect::<Vec<_>>().join(" ")
}

fn first_keyword(norm: &str) -> &str {
    norm.split(' ').next().unwrap_or("")
}

fn has_token(norm: &str, tok: &str) -> bool {
    norm.split(|c: char| !c.is_ascii_alphanumeric() && c != '_')
        .any(|t| t == tok)
}

/// Classify a SQL statement. Conservative by construction: anything it cannot parse
/// confidently comes back Unknown, and the shipped default policy denies Unknown.
pub fn classify_sql(sql: &str) -> PreflightReport {
    let norm = normalize(sql);
    if norm.is_empty() {
        return PreflightReport::unknown("empty statement after normalization");
    }

    let mut signals: Vec<String> = Vec::new();

    // Multiple statements in one call is a strong injection / smuggling signal.
    let stmt_count = norm.matches(';').count();
    if stmt_count > 1 || (stmt_count == 1 && !norm.trim_end().ends_with(';')) {
        signals.push("multi_statement".into());
    }

    let kw = first_keyword(&norm);
    let (class, mut rationale) = match kw {
        "SELECT" | "WITH" | "SHOW" | "EXPLAIN" | "DESCRIBE" => {
            (OperationClass::Read, "read-only statement".to_string())
        }
        "DROP" | "TRUNCATE" | "ALTER" | "GRANT" | "REVOKE" | "CREATE" => {
            signals.push(format!("ddl_{}", kw.to_lowercase()));
            (
                OperationClass::Destructive,
                format!("{kw} is schema- or privilege-altering"),
            )
        }
        "DELETE" | "UPDATE" => {
            if has_token(&norm, "WHERE") {
                signals.push("predicated_mutation".into());
                (
                    OperationClass::Write,
                    format!("{kw} with a WHERE predicate"),
                )
            } else {
                signals.push("unbounded_mutation".into());
                (
                    OperationClass::Destructive,
                    format!("{kw} with no WHERE clause affects every row"),
                )
            }
        }
        "INSERT" | "UPSERT" | "MERGE" | "COPY" => {
            signals.push("insert".into());
            (OperationClass::Write, format!("{kw} adds rows"))
        }
        _ => (
            OperationClass::Unknown,
            format!("unrecognised leading keyword '{kw}'"),
        ),
    };

    // A multi-statement payload escalates: the leading keyword no longer describes it.
    let class =
        if signals.iter().any(|s| s == "multi_statement") && class != OperationClass::Destructive {
            rationale.push_str("; escalated because the payload contains multiple statements");
            OperationClass::Destructive
        } else {
            class
        };

    if class == OperationClass::Read {
        signals.push("read".into());
    }

    PreflightReport {
        class,
        signals,
        // Rollback-based dry-run is meaningful only for statements that mutate and
        // that the connector can wrap in a transaction.
        dry_run_available: matches!(class, OperationClass::Write | OperationClass::Destructive)
            && !has_token(&norm, "COMMIT"),
        rationale,
    }
}

/// Classify a non-SQL tool call from its name and argument keys. Deliberately crude:
/// this is a prior that policy refines, not an authority.
pub fn classify_tool(name: &str, argument_keys: &[String]) -> PreflightReport {
    let n = name.to_ascii_lowercase();
    let destructive = [
        "delete",
        "destroy",
        "drop",
        "remove",
        "purge",
        "terminate",
        "revoke",
    ];
    let write = [
        "create", "update", "write", "put", "post", "patch", "set", "send", "upload", "merge",
    ];
    let read = [
        "get", "list", "read", "search", "describe", "fetch", "query", "find",
    ];

    let (class, rationale) = if destructive.iter().any(|k| n.contains(k)) {
        (
            OperationClass::Destructive,
            format!("tool name '{name}' matches a destructive verb"),
        )
    } else if write.iter().any(|k| n.contains(k)) {
        (
            OperationClass::Write,
            format!("tool name '{name}' matches a mutating verb"),
        )
    } else if read.iter().any(|k| n.contains(k)) {
        (
            OperationClass::Read,
            format!("tool name '{name}' matches a read verb"),
        )
    } else {
        (
            OperationClass::Unknown,
            format!("tool name '{name}' matches no known verb"),
        )
    };

    let mut signals = vec![format!("verb_{}", format!("{class:?}").to_lowercase())];
    for k in argument_keys {
        let lk = k.to_ascii_lowercase();
        if ["force", "cascade", "recursive", "all"].contains(&lk.as_str()) {
            signals.push(format!("arg_{lk}"));
        }
    }
    PreflightReport {
        class,
        signals,
        dry_run_available: false,
        rationale,
    }
}

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

    #[test]
    fn select_is_read() {
        assert_eq!(
            classify_sql("SELECT * FROM users").class,
            OperationClass::Read
        );
        assert_eq!(
            classify_sql("  with x as (select 1) select * from x").class,
            OperationClass::Read
        );
    }

    #[test]
    fn drop_and_truncate_are_destructive() {
        assert_eq!(
            classify_sql("DROP TABLE users;").class,
            OperationClass::Destructive
        );
        assert_eq!(
            classify_sql("truncate table events").class,
            OperationClass::Destructive
        );
        assert_eq!(
            classify_sql("ALTER TABLE users DROP COLUMN email").class,
            OperationClass::Destructive
        );
    }

    #[test]
    fn unbounded_mutation_is_destructive_but_predicated_is_write() {
        assert_eq!(
            classify_sql("DELETE FROM users").class,
            OperationClass::Destructive
        );
        assert_eq!(
            classify_sql("UPDATE users SET admin = true").class,
            OperationClass::Destructive
        );
        assert_eq!(
            classify_sql("DELETE FROM users WHERE id = 3").class,
            OperationClass::Write
        );
        assert_eq!(
            classify_sql("UPDATE users SET x = 1 WHERE id = 3").class,
            OperationClass::Write
        );
    }

    #[test]
    fn string_literals_cannot_forge_a_keyword() {
        // The literal contains "drop table" but the statement is a read.
        let r = classify_sql("SELECT 'drop table users' AS note");
        assert_eq!(
            r.class,
            OperationClass::Read,
            "literal must not be scanned for keywords"
        );
    }

    #[test]
    fn where_inside_a_literal_does_not_bound_a_delete() {
        // Without literal stripping this would be misclassified as a bounded Write.
        let r = classify_sql("DELETE FROM audit_log -- WHERE id = 1");
        assert_eq!(r.class, OperationClass::Destructive);
    }

    #[test]
    fn block_comments_cannot_hide_a_keyword() {
        let r = classify_sql("DROP/*sneaky*/ TABLE users");
        assert_eq!(r.class, OperationClass::Destructive);
    }

    #[test]
    fn stacked_statements_escalate() {
        let r = classify_sql("SELECT 1; DROP TABLE users;");
        assert_eq!(r.class, OperationClass::Destructive);
        assert!(r.signals.iter().any(|s| s == "multi_statement"));
    }

    #[test]
    fn unknown_is_not_silently_allowed() {
        assert_eq!(classify_sql("VACUUM FULL").class, OperationClass::Unknown);
        assert_eq!(classify_sql("").class, OperationClass::Unknown);
    }

    #[test]
    fn dry_run_offered_only_for_mutations() {
        assert!(!classify_sql("SELECT 1").dry_run_available);
        assert!(classify_sql("DELETE FROM t WHERE id=1").dry_run_available);
    }

    #[test]
    fn tool_name_classification() {
        assert_eq!(
            classify_tool("delete_issue", &[]).class,
            OperationClass::Destructive
        );
        assert_eq!(classify_tool("list_repos", &[]).class, OperationClass::Read);
        assert_eq!(classify_tool("create_pr", &[]).class, OperationClass::Write);
        assert_eq!(
            classify_tool("frobnicate", &[]).class,
            OperationClass::Unknown
        );
    }

    #[test]
    fn dangerous_argument_keys_surface_as_signals() {
        let r = classify_tool("remove_user", &["cascade".to_string()]);
        assert!(r.signals.iter().any(|s| s == "arg_cascade"));
    }
}