use super::Policy;
use crate::conn::OrFailure;
use crate::error::{Failure, Result};
use crate::output::Row;
use crate::sql::classify::Classification;
use crate::sql::guard::{admit, Admission};
use mysql_async::prelude::Queryable;
use mysql_async::{Conn, Params, Value as Wire};
const PARAMETER_MARKER: char = '?';
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Kind {
Text,
Integer,
Decimal,
Boolean,
Date,
}
impl Kind {
#[must_use]
pub const fn as_str(self) -> &'static str {
match self {
Self::Text => "text",
Self::Integer => "integer",
Self::Decimal => "decimal",
Self::Boolean => "boolean",
Self::Date => "date",
}
}
pub fn parse(text: &str) -> Result<Self> {
match text.trim().to_ascii_lowercase().as_str() {
"text" => Ok(Self::Text),
"integer" => Ok(Self::Integer),
"decimal" => Ok(Self::Decimal),
"boolean" => Ok(Self::Boolean),
"date" => Ok(Self::Date),
other => Err(Failure::usage(
"usage.unknown_parameter_kind",
format!("`{other}` is not a kind a parameter may be"),
)
.with_detail("detail", other)
.with_hint("one of: text, integer, decimal, boolean, date")),
}
}
#[must_use]
pub fn accepts(self, value: &str) -> bool {
match self {
Self::Text => true,
Self::Integer => value.parse::<i64>().is_ok(),
Self::Decimal => value.parse::<f64>().is_ok(),
Self::Boolean => matches!(
value.to_ascii_lowercase().as_str(),
"true" | "false" | "1" | "0"
),
Self::Date => is_calendar_date(value),
}
}
}
fn is_calendar_date(value: &str) -> bool {
let parts: Vec<&str> = value.split('-').collect();
let [year, month, day] = parts.as_slice() else {
return false;
};
year.len() == 4
&& year.parse::<u16>().is_ok()
&& month.parse::<u8>().is_ok_and(|m| (1..=12).contains(&m))
&& day.parse::<u8>().is_ok_and(|d| (1..=31).contains(&d))
}
#[derive(Debug)]
pub struct Gated {
sql: String,
admission: Admission,
values: Vec<String>,
}
impl Gated {
#[must_use]
pub fn sql(&self) -> &str {
&self.sql
}
#[must_use]
pub const fn classification(&self) -> Classification {
self.admission.classification()
}
#[must_use]
pub const fn kind(&self) -> &'static str {
self.admission.analysis().kind()
}
#[must_use]
pub const fn admission(&self) -> &Admission {
&self.admission
}
#[must_use]
pub fn values(&self) -> &[String] {
&self.values
}
#[must_use]
pub fn params(&self) -> Params {
bind(&self.values)
}
#[must_use]
pub fn with_sql(mut self, sql: String) -> Self {
self.sql = sql;
self
}
}
pub fn gate(sql: &str, values: &[String], policy: &Policy) -> Result<Gated> {
refuse_oversized_send(sql, values)?;
let admission = admit(sql, policy.parse)?;
debug_assert!(matches!(
admission.classification(),
Classification::Read
| Classification::Change
| Classification::Definition
| Classification::Administration
));
refuse_value_count_mismatch(admission.stripped().text(), values.len())?;
Ok(Gated {
sql: sql.to_owned(),
admission,
values: values.to_vec(),
})
}
fn refuse_oversized_send(sql: &str, values: &[String]) -> Result<()> {
let Some(ceiling) = crate::conn::handshake::PacketCeiling::in_force() else {
return Ok(());
};
let measured = measured_send(sql, values);
if measured <= ceiling {
return Ok(());
}
Err(Failure::limit(
"limit.packet_size",
format!("the command measures {measured} bytes and the destination accepts {ceiling}"),
)
.with_detail("detail", format!("{measured} > {ceiling}"))
.with_hint("split the send into smaller commands, or raise conn.max_packet_bytes"))
}
fn measured_send(sql: &str, values: &[String]) -> usize {
sql.len() + values.iter().map(String::len).sum::<usize>()
}
fn refuse_value_count_mismatch(stripped: &str, given: usize) -> Result<()> {
let markers = stripped.chars().filter(|c| *c == PARAMETER_MARKER).count();
if markers == given {
return Ok(());
}
Err(Failure::usage(
"usage.parameter_count",
format!("the statement has {markers} value markers and {given} values were given"),
)
.with_detail("detail", format!("{markers} != {given}"))
.with_hint("give exactly one --param for each marker, in order"))
}
#[must_use]
pub fn bind(values: &[String]) -> Params {
if values.is_empty() {
return Params::Empty;
}
Params::Positional(
values
.iter()
.map(|value| Wire::Bytes(value.clone().into_bytes()))
.collect(),
)
}
pub fn echo(gated: &Gated) {
tracing::debug!(
statement = gated.sql(),
values = gated.values().len(),
classification = gated.classification().as_str(),
"sending prepared statement; values are bound and never shown"
);
}
pub async fn exec_rows(
conn: &mut Conn,
sql: &str,
params: Params,
conversion: &crate::types::Conversion,
) -> Result<Vec<Row>> {
let mut result = conn.exec_iter(sql, params).await.or_failure()?;
let columns = result.columns_ref().to_vec();
let labels = crate::exec::read::column_names(&columns);
let mut rows = Vec::new();
while let Some(row) = result.next().await.or_failure()? {
rows.push(crate::exec::read::convert_row(
row, &columns, &labels, conversion,
)?);
}
Ok(rows)
}
pub async fn exec_drop(conn: &mut Conn, sql: &str, params: Params) -> Result<()> {
conn.exec_drop(sql, params).await.or_failure()
}
pub async fn exec_count(conn: &mut Conn, sql: &str, params: Params) -> Result<u64> {
let mut result = conn.exec_iter(sql, params).await.or_failure()?;
let first = result.next().await.or_failure()?;
result.drop_result().await.or_failure()?;
first
.and_then(|mut row| row.take::<Wire, _>(0))
.and_then(|wire| counted(&wire))
.ok_or_else(|| {
Failure::server(
"server.count_unreadable",
"the derived count did not return a single number",
)
})
}
fn counted(wire: &Wire) -> Option<u64> {
match wire {
Wire::UInt(number) => Some(*number),
Wire::Int(number) => u64::try_from(*number).ok(),
Wire::Bytes(bytes) => std::str::from_utf8(bytes).ok()?.trim().parse().ok(),
_ => None,
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::cli::globals::RowCountMode;
use crate::sql::ParseLimits;
use std::time::Duration;
fn policy() -> Policy {
Policy::new(
ParseLimits::default(),
100,
50,
RowCountMode::Changed,
";".to_owned(),
Duration::from_secs(30),
)
}
fn refusal(sql: &str, values: &[&str]) -> Failure {
let owned: Vec<String> = values.iter().map(|v| (*v).to_owned()).collect();
gate(sql, &owned, &policy()).expect_err("the statement must be refused")
}
fn admitted(sql: &str, values: &[&str]) -> Gated {
let owned: Vec<String> = values.iter().map(|v| (*v).to_owned()).collect();
gate(sql, &owned, &policy()).expect("the statement must be admitted")
}
#[derive(Clone, Default)]
struct Kept(std::sync::Arc<std::sync::Mutex<Vec<u8>>>);
impl Kept {
fn text(&self) -> String {
String::from_utf8(self.0.lock().expect("the channel is not poisoned").clone())
.expect("the channel carries utf8")
}
}
impl std::io::Write for Kept {
fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
self.0
.lock()
.expect("the channel is not poisoned")
.extend_from_slice(buf);
Ok(buf.len())
}
fn flush(&mut self) -> std::io::Result<()> {
Ok(())
}
}
impl<'a> tracing_subscriber::fmt::MakeWriter<'a> for Kept {
type Writer = Self;
fn make_writer(&'a self) -> Self::Writer {
self.clone()
}
}
fn echoed(gated: &Gated) -> String {
let kept = Kept::default();
let subscriber = tracing_subscriber::fmt()
.with_writer(kept.clone())
.with_max_level(tracing::Level::DEBUG)
.with_ansi(false)
.finish();
tracing::subscriber::with_default(subscriber, || echo(gated));
kept.text()
}
#[test]
fn the_echo_carries_the_exact_statement_and_never_a_value() {
let secret = "senha-que-nunca-pode-aparecer";
let gated = admitted("SELECT a FROM t WHERE b = ? AND c = ?", &[secret, "outro"]);
let written = echoed(&gated);
assert!(
written.contains("SELECT a FROM t WHERE b = ? AND c = ?"),
"the echo has to carry the statement that is sent: {written}"
);
assert_eq!(
written.matches(secret).count(),
0,
"a bound value reached the auxiliary channel: {written}"
);
assert!(
written.contains("values=2"),
"the values are named by their count, and the count has to be right: {written}"
);
assert!(
written.contains("classification=\"read\"") || written.contains("classification=read"),
"the echo has to say what the statement does: {written}"
);
}
#[test]
fn the_multiple_command_refusal_runs_before_every_other_layer() {
let failure = refusal("SELECT ?; DELETE FROM users", &["a", "b"]);
assert_eq!(failure.code(), "sql.multiple_statements");
}
#[test]
fn a_reach_for_the_servers_filesystem_is_refused_before_the_marker_count() {
let failure = refusal("SELECT LOAD_FILE('/etc/passwd')", &["extra"]);
assert_eq!(failure.code(), "sql.server_file_read");
}
#[test]
fn an_unrecognised_shape_is_refused_and_never_treated_as_a_read() {
let failure = refusal("SELECT FROM WHERE", &[]);
assert!(
matches!(failure.code(), "sql.unparsable" | "sql.unclassified"),
"unexpected code {}",
failure.code()
);
assert_eq!(failure.exit_number().code(), 3);
}
#[test]
fn the_classification_travels_with_the_admitted_statement() {
assert_eq!(
admitted("SELECT a FROM t", &[]).classification(),
Classification::Read
);
assert_eq!(
admitted("DELETE FROM t WHERE a = ?", &["1"]).classification(),
Classification::Change
);
assert_eq!(
admitted("/* SELECT */ DELETE FROM users WHERE a = 1", &[]).classification(),
Classification::Change,
"a comment must not move the decision"
);
}
#[test]
fn too_few_values_are_refused_before_any_connection_is_opened() {
let failure = refusal("SELECT a FROM t WHERE a = ? AND b = ?", &["one"]);
assert_eq!(failure.code(), "usage.parameter_count");
assert_eq!(failure.exit_number().code(), 2);
}
#[test]
fn too_many_values_are_refused_as_well() {
assert_eq!(
refusal("SELECT a FROM t WHERE a = ?", &["one", "two"]).code(),
"usage.parameter_count"
);
}
#[test]
fn a_marker_inside_a_literal_is_not_counted() {
assert_eq!(admitted("SELECT 'why?' AS note", &[]).values().len(), 0);
assert_eq!(
admitted("SELECT 'why?' FROM t WHERE a = ?", &["one"])
.values()
.len(),
1
);
}
#[test]
fn a_value_carrying_a_command_stays_a_value() {
let gated = admitted(
"SELECT * FROM clientes WHERE nome = ?",
&["O'Brien'; DROP TABLE clientes; --"],
);
assert_eq!(
gated.sql(),
"SELECT * FROM clientes WHERE nome = ?",
"the statement text is untouched by the value"
);
assert_eq!(gated.classification(), Classification::Read);
match gated.params() {
Params::Positional(values) => {
assert_eq!(values.len(), 1);
assert_eq!(
values[0],
Wire::Bytes(b"O'Brien'; DROP TABLE clientes; --".to_vec()),
"the value travels whole, as a value"
);
}
other => panic!("values must be bound positionally, got {other:?}"),
}
}
#[test]
fn every_kind_accepts_what_it_names_and_refuses_what_it_does_not() {
assert!(Kind::Integer.accepts("-42") && !Kind::Integer.accepts("4.2"));
assert!(Kind::Decimal.accepts("4.2"));
assert!(Kind::Boolean.accepts("TRUE") && Kind::Boolean.accepts("0"));
assert!(!Kind::Boolean.accepts("maybe"));
assert!(Kind::Date.accepts("2026-08-07"));
assert!(
!Kind::Date.accepts("2026-13-01"),
"a thirteenth month is not one"
);
assert!(
!Kind::Date.accepts("2026-01"),
"an incomplete date is not one"
);
assert!(Kind::Text.accepts("anything at all; DROP TABLE t"));
}
#[test]
fn the_send_is_measured_with_the_values_applied() {
let statement = "INSERT INTO t (a, b) VALUES (?, ?)";
let values = vec!["x".repeat(1000), "y".repeat(2000)];
assert_eq!(
measured_send(statement, &values),
statement.len() + 3000,
"the statement and every value it carries are one send"
);
assert_eq!(measured_send(statement, &[]), statement.len());
}
#[test]
fn a_statement_without_values_binds_nothing() {
assert_eq!(admitted("SELECT 1", &[]).params(), Params::Empty);
}
#[test]
fn a_count_reads_a_number_in_either_published_shape() {
assert_eq!(counted(&Wire::UInt(42)), Some(42));
assert_eq!(counted(&Wire::Int(42)), Some(42));
assert_eq!(
counted(&Wire::Bytes(b"18446744073709551615".to_vec())),
Some(u64::MAX),
"a count above the safe range arrives as text"
);
assert_eq!(counted(&Wire::NULL), None);
assert_eq!(counted(&Wire::Int(-1)), None, "a count is never negative");
}
#[test]
fn appending_this_tools_own_clause_keeps_the_admission_that_cleared_it() {
let gated = admitted("SELECT a FROM t", &[]);
let widened = gated.with_sql("SELECT a FROM t\nLIMIT 10".to_owned());
assert_eq!(widened.sql(), "SELECT a FROM t\nLIMIT 10");
assert_eq!(widened.classification(), Classification::Read);
}
}