Skip to main content

mariadb_cli/exec/
prepare.rs

1//! The single gateway every caller statement passes through.
2//!
3//! Nothing in this crate sends a caller's text to the server except through
4//! this module, so the order of the defences exists in one place only and
5//! cannot be reordered by accident at a call site.
6//!
7//! # The prepared protocol is the defence
8//!
9//! [`exec_rows`] and [`exec_drop`] call the driver's `exec_*` family, which
10//! speaks the binary prepared protocol. The server manual requires the text of
11//! a prepared statement to represent one single statement, so a text carrying
12//! two commands is refused by the server itself. That refusal does not depend
13//! on this tool reading the text correctly, which is what makes it the
14//! structural defence rather than one more textual check.
15//!
16//! The driver's `query_*` family speaks the text protocol and hands the server
17//! a text it is free to split. It is never used here. Swapping one for the
18//! other would look like a harmless simplification and would remove the whole
19//! defence, which is why the reason is written next to the code.
20//!
21//! # A value is never pasted into the text
22//!
23//! A caller value travels bound and never as text spliced into the statement.
24//! Splicing is injection, whatever quoting is applied first. An object name
25//! cannot travel as a parameter, and the one sanctioned way to put one into a
26//! statement is [`crate::sql::ident::quote`].
27
28use 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
37/// The marker a bound value occupies in a statement.
38const PARAMETER_MARKER: char = '?';
39
40/// The kinds a declared parameter may be.
41///
42/// The list is closed: a kind absent from it does not exist, so a declaration
43/// naming one is refused when it is written rather than when it is run.
44#[derive(Debug, Clone, Copy, PartialEq, Eq)]
45pub enum Kind {
46    /// Free text.
47    Text,
48    /// A whole number, which may be negative.
49    Integer,
50    /// A number with a fractional part.
51    Decimal,
52    /// A truth value.
53    Boolean,
54    /// A calendar date, written as year, month and day.
55    Date,
56}
57
58impl Kind {
59    /// The stable name a declaration writes.
60    #[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    /// Reads a kind out of a declaration.
72    ///
73    /// # Errors
74    ///
75    /// Returns a usage failure naming every kind that exists.
76    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    /// Whether one value belongs to this kind.
93    #[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
108/// Whether a text is a date written as year, month and day.
109fn 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/// A statement that passed every defence and the values bound to it.
121///
122/// Holding the admission rather than only the classification keeps the syntax
123/// tree available to the ceilings that need to read it, so nothing downstream
124/// has to parse the text a second time.
125#[derive(Debug)]
126pub struct Gated {
127    sql: String,
128    admission: Admission,
129    values: Vec<String>,
130}
131
132impl Gated {
133    /// The exact text that will reach the server.
134    #[must_use]
135    pub fn sql(&self) -> &str {
136        &self.sql
137    }
138
139    /// What the statement does.
140    #[must_use]
141    pub const fn classification(&self) -> Classification {
142        self.admission.classification()
143    }
144
145    /// The recognised statement shape, such as `select` or `delete`.
146    #[must_use]
147    pub const fn kind(&self) -> &'static str {
148        self.admission.analysis().kind()
149    }
150
151    /// The admission, with the syntax tree the defences were read from.
152    #[must_use]
153    pub const fn admission(&self) -> &Admission {
154        &self.admission
155    }
156
157    /// The values bound to the markers, in the order they were given.
158    #[must_use]
159    pub fn values(&self) -> &[String] {
160        &self.values
161    }
162
163    /// The bound values in the shape the driver sends them.
164    #[must_use]
165    pub fn params(&self) -> Params {
166        bind(&self.values)
167    }
168
169    /// Replaces the text while keeping the admission that cleared it.
170    ///
171    /// Used where this tool appends its own row ceiling to a query it has
172    /// already admitted. The appended clause is written by this tool and never
173    /// by the caller, so re-admitting it would only re-prove what is known.
174    #[must_use]
175    pub fn with_sql(mut self, sql: String) -> Self {
176        self.sql = sql;
177        self
178    }
179}
180
181/// Admits one caller statement, or says exactly why it is refused.
182///
183/// The order is the design and is fixed:
184///
185/// 1. The structural refusals run over the syntax tree and over the text with
186///    comments and literals blanked, before anything is sent.
187/// 2. The classification is read from that same tree. A shape the classifier
188///    does not recognise is refused here and is never carried on as a read.
189/// 3. The count of bound values is checked against the count of markers, so a
190///    mismatch costs no connection.
191///
192/// The size of the send is measured before any of that, because it is the one
193/// refusal whose absence is not a wrong answer but a lost connection: a command
194/// past the destination's packet ceiling is not rejected by the server, it
195/// makes the server close the channel, and the caller is then told the network
196/// is unreachable about a command that never had a chance of arriving.
197///
198/// # Errors
199///
200/// Returns a limit failure when the send is larger than the destination
201/// accepts. Returns a validation failure when the statement carries more than
202/// one command, reaches the server's filesystem, or has an unrecognised shape.
203/// Returns a usage failure when the number of values does not match the number
204/// of markers.
205pub 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    // The classifier refuses an unrecognised shape inside `admit`, so reaching
210    // this line already proves the statement was recognised. The assertion is
211    // kept as an explicit statement of that dependency.
212    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
229/// Refuses a send larger than the destination will accept in one piece.
230///
231/// The measurement is taken with the values counted in, because that is what
232/// travels: the statement is one part of the send and every bound value is
233/// another, and a caller writing many values at once reaches the ceiling with a
234/// statement of two lines. Measuring the text alone would let exactly the send
235/// this refusal exists for through.
236///
237/// A ceiling that was never settled means no server has been reached and no key
238/// was written, so there is no send to measure and nothing is refused. Choosing
239/// a number here instead would refuse a command no destination objected to.
240///
241/// # Errors
242///
243/// Returns a limit failure naming the size measured and the ceiling it passed.
244fn 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
260/// The size of what this send puts on the channel, in bytes.
261///
262/// The statement and every value it carries are counted together, because the
263/// ceiling applies to the send and not to either half of it.
264fn measured_send(sql: &str, values: &[String]) -> usize {
265    sql.len() + values.iter().map(String::len).sum::<usize>()
266}
267
268/// Refuses a statement whose markers and values do not match.
269///
270/// The markers are counted over the blanked text, so a marker that is really a
271/// character inside a text literal is not counted and a legitimate statement is
272/// not refused for it.
273///
274/// # Errors
275///
276/// Returns a usage failure naming both counts.
277fn 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/// Turns caller values into the shape the driver sends.
291///
292/// Every value is bound as text and the server converts it to the column's own
293/// type. Deciding the type here would mean guessing, and a wrong guess changes
294/// what the statement matches. Binding as text never changes the statement,
295/// because a bound value is never part of the statement.
296#[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
309/// Writes the exact statement to the auxiliary channel, never the primary one.
310///
311/// The values are shown as markers rather than as themselves. A value may be a
312/// credential, and a diagnostic that prints one has leaked it into every log
313/// that captured the auxiliary channel.
314pub 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
323/// Runs a prepared statement and collects the rows of its first result set.
324///
325/// # Errors
326///
327/// Returns the mapped driver failure when the server refuses the statement or
328/// the channel is lost, and a limit failure when a value exceeds its ceiling.
329pub async fn exec_rows(
330    conn: &mut Conn,
331    sql: &str,
332    params: Params,
333    conversion: &crate::types::Conversion,
334) -> Result<Vec<Row>> {
335    // The prepared protocol: `exec_iter`, never `query_iter`. See the module
336    // documentation for why this choice is the product's defence.
337    let mut result = conn.exec_iter(sql, params).await.or_failure()?;
338
339    let columns = result.columns_ref().to_vec();
340    // Worked out once, outside the loop: they are the same for every row.
341    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
351/// Runs a prepared statement that returns no rows.
352///
353/// # Errors
354///
355/// Returns the mapped driver failure when the server refuses the statement.
356pub async fn exec_drop(conn: &mut Conn, sql: &str, params: Params) -> Result<()> {
357    conn.exec_drop(sql, params).await.or_failure()
358}
359
360/// Reads one whole number out of a single-cell result.
361///
362/// # Errors
363///
364/// Returns the mapped driver failure, or a server failure when the answer did
365/// not carry the single number it was asked for.
366pub async fn exec_count(conn: &mut Conn, sql: &str, params: Params) -> Result<u64> {
367    // Deliberately not routed through `exec_rows`. A count is a single number
368    // and can never be a byte column, so it needs none of the shaping a row
369    // does; asking for a conversion here would make every caller carry one for
370    // a value it can have no effect on.
371    let mut result = conn.exec_iter(sql, params).await.or_failure()?;
372    let first = result.next().await.or_failure()?;
373    // The rest of the answer is drained so the connection is left usable, which
374    // matters because this runs before the work the caller actually asked for.
375    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
388/// Reads a whole number out of a cell, whichever shape it arrived in.
389///
390/// Reads a count straight off the wire.
391///
392/// A count above the range a number can carry without losing a digit arrives as
393/// text, by the published type map, so both shapes have to be accepted here.
394fn 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    /// A channel that keeps what was written to it, so a diagnostic can be read
432    /// back by the test that provoked it.
433    #[derive(Clone, Default)]
434    struct Kept(std::sync::Arc<std::sync::Mutex<Vec<u8>>>);
435
436    impl Kept {
437        /// Everything written so far, as text.
438        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    /// What the echo writes for one admitted statement.
467    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    /// FR-098. The echo carries the exact text that reaches the server, and the
479    /// values are named by their count alone.
480    ///
481    /// Both halves are one test because either one alone is worthless. An echo
482    /// that named the values would leak whatever a caller bound — a password,
483    /// a document number — into every log that captured the auxiliary channel,
484    /// which is the leak FR-051 exists to forbid. An echo that hid the values
485    /// but printed a statement other than the one that was sent would send
486    /// whoever is investigating after the wrong text.
487    ///
488    /// The value below is one nothing else in the diagnostic could produce, so
489    /// finding it anywhere in what was written is proof it travelled.
490    #[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    /// The structural refusals run before anything else, so a text carrying two
517    /// commands never reaches the count of markers, let alone the server.
518    #[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    /// A shape the classifier does not recognise is refused, and is never let
531    /// through as a read.
532    #[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    /// A marker inside a text literal is not a marker, so counting it would
576    /// refuse a legitimate statement.
577    #[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    /// The whole point of a bound value: whatever it contains, it stays a
589    /// value and never becomes part of the statement.
590    #[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    /// FR-084. The size is measured with the values counted in, because that is
634    /// what travels. Measuring the text alone would let a two-line statement
635    /// carrying a hundred large values through, which is the send the ceiling
636    /// exists for.
637    #[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}