1use super::Policy;
29use crate::conn::OrFailure;
30use crate::error::{Failure, Result};
31use crate::output::Row;
32use crate::sql::classify::Classification;
33use crate::sql::guard::{admit, Admission};
34use mysql_async::prelude::Queryable;
35use mysql_async::{Conn, Params, Value as Wire};
36
37const PARAMETER_MARKER: char = '?';
39
40#[derive(Debug, Clone, Copy, PartialEq, Eq)]
45pub enum Kind {
46 Text,
48 Integer,
50 Decimal,
52 Boolean,
54 Date,
56}
57
58impl Kind {
59 #[must_use]
61 pub const fn as_str(self) -> &'static str {
62 match self {
63 Self::Text => "text",
64 Self::Integer => "integer",
65 Self::Decimal => "decimal",
66 Self::Boolean => "boolean",
67 Self::Date => "date",
68 }
69 }
70
71 pub fn parse(text: &str) -> Result<Self> {
77 match text.trim().to_ascii_lowercase().as_str() {
78 "text" => Ok(Self::Text),
79 "integer" => Ok(Self::Integer),
80 "decimal" => Ok(Self::Decimal),
81 "boolean" => Ok(Self::Boolean),
82 "date" => Ok(Self::Date),
83 other => Err(Failure::usage(
84 "usage.unknown_parameter_kind",
85 format!("`{other}` is not a kind a parameter may be"),
86 )
87 .with_detail("detail", other)
88 .with_hint("one of: text, integer, decimal, boolean, date")),
89 }
90 }
91
92 #[must_use]
94 pub fn accepts(self, value: &str) -> bool {
95 match self {
96 Self::Text => true,
97 Self::Integer => value.parse::<i64>().is_ok(),
98 Self::Decimal => value.parse::<f64>().is_ok(),
99 Self::Boolean => matches!(
100 value.to_ascii_lowercase().as_str(),
101 "true" | "false" | "1" | "0"
102 ),
103 Self::Date => is_calendar_date(value),
104 }
105 }
106}
107
108fn is_calendar_date(value: &str) -> bool {
110 let parts: Vec<&str> = value.split('-').collect();
111 let [year, month, day] = parts.as_slice() else {
112 return false;
113 };
114 year.len() == 4
115 && year.parse::<u16>().is_ok()
116 && month.parse::<u8>().is_ok_and(|m| (1..=12).contains(&m))
117 && day.parse::<u8>().is_ok_and(|d| (1..=31).contains(&d))
118}
119
120#[derive(Debug)]
126pub struct Gated {
127 sql: String,
128 admission: Admission,
129 values: Vec<String>,
130}
131
132impl Gated {
133 #[must_use]
135 pub fn sql(&self) -> &str {
136 &self.sql
137 }
138
139 #[must_use]
141 pub const fn classification(&self) -> Classification {
142 self.admission.classification()
143 }
144
145 #[must_use]
147 pub const fn kind(&self) -> &'static str {
148 self.admission.analysis().kind()
149 }
150
151 #[must_use]
153 pub const fn admission(&self) -> &Admission {
154 &self.admission
155 }
156
157 #[must_use]
159 pub fn values(&self) -> &[String] {
160 &self.values
161 }
162
163 #[must_use]
165 pub fn params(&self) -> Params {
166 bind(&self.values)
167 }
168
169 #[must_use]
175 pub fn with_sql(mut self, sql: String) -> Self {
176 self.sql = sql;
177 self
178 }
179}
180
181pub fn gate(sql: &str, values: &[String], policy: &Policy) -> Result<Gated> {
206 refuse_oversized_send(sql, values)?;
207
208 let admission = admit(sql, policy.parse)?;
209 debug_assert!(matches!(
213 admission.classification(),
214 Classification::Read
215 | Classification::Change
216 | Classification::Definition
217 | Classification::Administration
218 ));
219
220 refuse_value_count_mismatch(admission.stripped().text(), values.len())?;
221
222 Ok(Gated {
223 sql: sql.to_owned(),
224 admission,
225 values: values.to_vec(),
226 })
227}
228
229fn refuse_oversized_send(sql: &str, values: &[String]) -> Result<()> {
245 let Some(ceiling) = crate::conn::handshake::PacketCeiling::in_force() else {
246 return Ok(());
247 };
248 let measured = measured_send(sql, values);
249 if measured <= ceiling {
250 return Ok(());
251 }
252 Err(Failure::limit(
253 "limit.packet_size",
254 format!("the command measures {measured} bytes and the destination accepts {ceiling}"),
255 )
256 .with_detail("detail", format!("{measured} > {ceiling}"))
257 .with_hint("split the send into smaller commands, or raise conn.max_packet_bytes"))
258}
259
260fn measured_send(sql: &str, values: &[String]) -> usize {
265 sql.len() + values.iter().map(String::len).sum::<usize>()
266}
267
268fn refuse_value_count_mismatch(stripped: &str, given: usize) -> Result<()> {
278 let markers = stripped.chars().filter(|c| *c == PARAMETER_MARKER).count();
279 if markers == given {
280 return Ok(());
281 }
282 Err(Failure::usage(
283 "usage.parameter_count",
284 format!("the statement has {markers} value markers and {given} values were given"),
285 )
286 .with_detail("detail", format!("{markers} != {given}"))
287 .with_hint("give exactly one --param for each marker, in order"))
288}
289
290#[must_use]
297pub fn bind(values: &[String]) -> Params {
298 if values.is_empty() {
299 return Params::Empty;
300 }
301 Params::Positional(
302 values
303 .iter()
304 .map(|value| Wire::Bytes(value.clone().into_bytes()))
305 .collect(),
306 )
307}
308
309pub fn echo(gated: &Gated) {
315 tracing::debug!(
316 statement = gated.sql(),
317 values = gated.values().len(),
318 classification = gated.classification().as_str(),
319 "sending prepared statement; values are bound and never shown"
320 );
321}
322
323pub async fn exec_rows(
330 conn: &mut Conn,
331 sql: &str,
332 params: Params,
333 conversion: &crate::types::Conversion,
334) -> Result<Vec<Row>> {
335 let mut result = conn.exec_iter(sql, params).await.or_failure()?;
338
339 let columns = result.columns_ref().to_vec();
340 let labels = crate::exec::read::column_names(&columns);
342 let mut rows = Vec::new();
343 while let Some(row) = result.next().await.or_failure()? {
344 rows.push(crate::exec::read::convert_row(
345 row, &columns, &labels, conversion,
346 )?);
347 }
348 Ok(rows)
349}
350
351pub async fn exec_drop(conn: &mut Conn, sql: &str, params: Params) -> Result<()> {
357 conn.exec_drop(sql, params).await.or_failure()
358}
359
360pub async fn exec_count(conn: &mut Conn, sql: &str, params: Params) -> Result<u64> {
367 let mut result = conn.exec_iter(sql, params).await.or_failure()?;
372 let first = result.next().await.or_failure()?;
373 result.drop_result().await.or_failure()?;
376
377 first
378 .and_then(|mut row| row.take::<Wire, _>(0))
379 .and_then(|wire| counted(&wire))
380 .ok_or_else(|| {
381 Failure::server(
382 "server.count_unreadable",
383 "the derived count did not return a single number",
384 )
385 })
386}
387
388fn counted(wire: &Wire) -> Option<u64> {
395 match wire {
396 Wire::UInt(number) => Some(*number),
397 Wire::Int(number) => u64::try_from(*number).ok(),
398 Wire::Bytes(bytes) => std::str::from_utf8(bytes).ok()?.trim().parse().ok(),
399 _ => None,
400 }
401}
402
403#[cfg(test)]
404mod tests {
405 use super::*;
406 use crate::cli::globals::RowCountMode;
407 use crate::sql::ParseLimits;
408 use std::time::Duration;
409
410 fn policy() -> Policy {
411 Policy::new(
412 ParseLimits::default(),
413 100,
414 50,
415 RowCountMode::Changed,
416 ";".to_owned(),
417 Duration::from_secs(30),
418 )
419 }
420
421 fn refusal(sql: &str, values: &[&str]) -> Failure {
422 let owned: Vec<String> = values.iter().map(|v| (*v).to_owned()).collect();
423 gate(sql, &owned, &policy()).expect_err("the statement must be refused")
424 }
425
426 fn admitted(sql: &str, values: &[&str]) -> Gated {
427 let owned: Vec<String> = values.iter().map(|v| (*v).to_owned()).collect();
428 gate(sql, &owned, &policy()).expect("the statement must be admitted")
429 }
430
431 #[derive(Clone, Default)]
434 struct Kept(std::sync::Arc<std::sync::Mutex<Vec<u8>>>);
435
436 impl Kept {
437 fn text(&self) -> String {
439 String::from_utf8(self.0.lock().expect("the channel is not poisoned").clone())
440 .expect("the channel carries utf8")
441 }
442 }
443
444 impl std::io::Write for Kept {
445 fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
446 self.0
447 .lock()
448 .expect("the channel is not poisoned")
449 .extend_from_slice(buf);
450 Ok(buf.len())
451 }
452
453 fn flush(&mut self) -> std::io::Result<()> {
454 Ok(())
455 }
456 }
457
458 impl<'a> tracing_subscriber::fmt::MakeWriter<'a> for Kept {
459 type Writer = Self;
460
461 fn make_writer(&'a self) -> Self::Writer {
462 self.clone()
463 }
464 }
465
466 fn echoed(gated: &Gated) -> String {
468 let kept = Kept::default();
469 let subscriber = tracing_subscriber::fmt()
470 .with_writer(kept.clone())
471 .with_max_level(tracing::Level::DEBUG)
472 .with_ansi(false)
473 .finish();
474 tracing::subscriber::with_default(subscriber, || echo(gated));
475 kept.text()
476 }
477
478 #[test]
491 fn the_echo_carries_the_exact_statement_and_never_a_value() {
492 let secret = "senha-que-nunca-pode-aparecer";
493 let gated = admitted("SELECT a FROM t WHERE b = ? AND c = ?", &[secret, "outro"]);
494
495 let written = echoed(&gated);
496
497 assert!(
498 written.contains("SELECT a FROM t WHERE b = ? AND c = ?"),
499 "the echo has to carry the statement that is sent: {written}"
500 );
501 assert_eq!(
502 written.matches(secret).count(),
503 0,
504 "a bound value reached the auxiliary channel: {written}"
505 );
506 assert!(
507 written.contains("values=2"),
508 "the values are named by their count, and the count has to be right: {written}"
509 );
510 assert!(
511 written.contains("classification=\"read\"") || written.contains("classification=read"),
512 "the echo has to say what the statement does: {written}"
513 );
514 }
515
516 #[test]
519 fn the_multiple_command_refusal_runs_before_every_other_layer() {
520 let failure = refusal("SELECT ?; DELETE FROM users", &["a", "b"]);
521 assert_eq!(failure.code(), "sql.multiple_statements");
522 }
523
524 #[test]
525 fn a_reach_for_the_servers_filesystem_is_refused_before_the_marker_count() {
526 let failure = refusal("SELECT LOAD_FILE('/etc/passwd')", &["extra"]);
527 assert_eq!(failure.code(), "sql.server_file_read");
528 }
529
530 #[test]
533 fn an_unrecognised_shape_is_refused_and_never_treated_as_a_read() {
534 let failure = refusal("SELECT FROM WHERE", &[]);
535 assert!(
536 matches!(failure.code(), "sql.unparsable" | "sql.unclassified"),
537 "unexpected code {}",
538 failure.code()
539 );
540 assert_eq!(failure.exit_number().code(), 3);
541 }
542
543 #[test]
544 fn the_classification_travels_with_the_admitted_statement() {
545 assert_eq!(
546 admitted("SELECT a FROM t", &[]).classification(),
547 Classification::Read
548 );
549 assert_eq!(
550 admitted("DELETE FROM t WHERE a = ?", &["1"]).classification(),
551 Classification::Change
552 );
553 assert_eq!(
554 admitted("/* SELECT */ DELETE FROM users WHERE a = 1", &[]).classification(),
555 Classification::Change,
556 "a comment must not move the decision"
557 );
558 }
559
560 #[test]
561 fn too_few_values_are_refused_before_any_connection_is_opened() {
562 let failure = refusal("SELECT a FROM t WHERE a = ? AND b = ?", &["one"]);
563 assert_eq!(failure.code(), "usage.parameter_count");
564 assert_eq!(failure.exit_number().code(), 2);
565 }
566
567 #[test]
568 fn too_many_values_are_refused_as_well() {
569 assert_eq!(
570 refusal("SELECT a FROM t WHERE a = ?", &["one", "two"]).code(),
571 "usage.parameter_count"
572 );
573 }
574
575 #[test]
578 fn a_marker_inside_a_literal_is_not_counted() {
579 assert_eq!(admitted("SELECT 'why?' AS note", &[]).values().len(), 0);
580 assert_eq!(
581 admitted("SELECT 'why?' FROM t WHERE a = ?", &["one"])
582 .values()
583 .len(),
584 1
585 );
586 }
587
588 #[test]
591 fn a_value_carrying_a_command_stays_a_value() {
592 let gated = admitted(
593 "SELECT * FROM clientes WHERE nome = ?",
594 &["O'Brien'; DROP TABLE clientes; --"],
595 );
596 assert_eq!(
597 gated.sql(),
598 "SELECT * FROM clientes WHERE nome = ?",
599 "the statement text is untouched by the value"
600 );
601 assert_eq!(gated.classification(), Classification::Read);
602 match gated.params() {
603 Params::Positional(values) => {
604 assert_eq!(values.len(), 1);
605 assert_eq!(
606 values[0],
607 Wire::Bytes(b"O'Brien'; DROP TABLE clientes; --".to_vec()),
608 "the value travels whole, as a value"
609 );
610 }
611 other => panic!("values must be bound positionally, got {other:?}"),
612 }
613 }
614
615 #[test]
616 fn every_kind_accepts_what_it_names_and_refuses_what_it_does_not() {
617 assert!(Kind::Integer.accepts("-42") && !Kind::Integer.accepts("4.2"));
618 assert!(Kind::Decimal.accepts("4.2"));
619 assert!(Kind::Boolean.accepts("TRUE") && Kind::Boolean.accepts("0"));
620 assert!(!Kind::Boolean.accepts("maybe"));
621 assert!(Kind::Date.accepts("2026-08-07"));
622 assert!(
623 !Kind::Date.accepts("2026-13-01"),
624 "a thirteenth month is not one"
625 );
626 assert!(
627 !Kind::Date.accepts("2026-01"),
628 "an incomplete date is not one"
629 );
630 assert!(Kind::Text.accepts("anything at all; DROP TABLE t"));
631 }
632
633 #[test]
638 fn the_send_is_measured_with_the_values_applied() {
639 let statement = "INSERT INTO t (a, b) VALUES (?, ?)";
640 let values = vec!["x".repeat(1000), "y".repeat(2000)];
641 assert_eq!(
642 measured_send(statement, &values),
643 statement.len() + 3000,
644 "the statement and every value it carries are one send"
645 );
646 assert_eq!(measured_send(statement, &[]), statement.len());
647 }
648
649 #[test]
650 fn a_statement_without_values_binds_nothing() {
651 assert_eq!(admitted("SELECT 1", &[]).params(), Params::Empty);
652 }
653
654 #[test]
655 fn a_count_reads_a_number_in_either_published_shape() {
656 assert_eq!(counted(&Wire::UInt(42)), Some(42));
657 assert_eq!(counted(&Wire::Int(42)), Some(42));
658 assert_eq!(
659 counted(&Wire::Bytes(b"18446744073709551615".to_vec())),
660 Some(u64::MAX),
661 "a count above the safe range arrives as text"
662 );
663 assert_eq!(counted(&Wire::NULL), None);
664 assert_eq!(counted(&Wire::Int(-1)), None, "a count is never negative");
665 }
666
667 #[test]
668 fn appending_this_tools_own_clause_keeps_the_admission_that_cleared_it() {
669 let gated = admitted("SELECT a FROM t", &[]);
670 let widened = gated.with_sql("SELECT a FROM t\nLIMIT 10".to_owned());
671 assert_eq!(widened.sql(), "SELECT a FROM t\nLIMIT 10");
672 assert_eq!(widened.classification(), Classification::Read);
673 }
674}