use serde::{Deserialize, Serialize};
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum OperationClass {
Read,
Write,
Destructive,
Unknown,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PreflightReport {
pub class: OperationClass,
pub signals: Vec<String>,
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(),
}
}
}
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 {
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;
}
}
}
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)
}
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();
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}'"),
),
};
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,
dry_run_available: matches!(class, OperationClass::Write | OperationClass::Destructive)
&& !has_token(&norm, "COMMIT"),
rationale,
}
}
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() {
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() {
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"));
}
}