Skip to main content

sqlx_mysql/options/
connect.rs

1use crate::connection::ConnectOptions;
2use crate::error::Error;
3use crate::executor::Executor;
4use crate::{MySqlConnectOptions, MySqlConnection};
5use log::LevelFilter;
6use sqlx_core::sql_str::AssertSqlSafe;
7use sqlx_core::Url;
8use std::time::Duration;
9
10impl ConnectOptions for MySqlConnectOptions {
11    type Connection = MySqlConnection;
12
13    fn from_url(url: &Url) -> Result<Self, Error> {
14        Self::parse_from_url(url)
15    }
16
17    fn to_url_lossy(&self) -> Url {
18        self.build_url()
19    }
20
21    async fn connect(&self) -> Result<Self::Connection, Error>
22    where
23        Self::Connection: Sized,
24    {
25        let mut conn = MySqlConnection::establish(self).await?;
26
27        // After the connection is established, we initialize by configuring a few
28        // connection parameters
29
30        if let Some(statement) = self.connect_init_statement() {
31            conn.execute(AssertSqlSafe(statement)).await?;
32        }
33
34        Ok(conn)
35    }
36
37    fn log_statements(mut self, level: LevelFilter) -> Self {
38        self.log_settings.log_statements(level);
39        self
40    }
41
42    fn log_slow_statements(mut self, level: LevelFilter, duration: Duration) -> Self {
43        self.log_settings.log_slow_statements(level, duration);
44        self
45    }
46}
47
48impl MySqlConnectOptions {
49    /// Build the `SET ...;` statement sent right after connecting.
50    ///
51    /// Kept as a pure function of the options (no I/O) so it can be
52    /// unit-tested without a live connection.
53    fn connect_init_statement(&self) -> Option<String> {
54        // https://mariadb.com/kb/en/sql-mode/
55
56        // PIPES_AS_CONCAT - Allows using the pipe character (ASCII 124) as string concatenation operator.
57        //                   This means that "A" || "B" can be used in place of CONCAT("A", "B").
58
59        // NO_ENGINE_SUBSTITUTION - If not set, if the available storage engine specified by a CREATE TABLE is
60        //                          not available, a warning is given and the default storage
61        //                          engine is used instead.
62
63        // NO_ZERO_DATE - Don't allow '0000-00-00'. This is invalid in Rust.
64
65        // NO_ZERO_IN_DATE - Don't allow 'YYYY-00-00'. This is invalid in Rust.
66
67        // --
68
69        // Setting the time zone allows us to assume that the output
70        // from a TIMESTAMP field is UTC
71
72        // --
73
74        // https://mathiasbynens.be/notes/mysql-utf8mb4
75
76        let mut sql_mode = Vec::new();
77        if self.pipes_as_concat {
78            sql_mode.push(r#"PIPES_AS_CONCAT"#);
79        }
80        if self.no_engine_substitution {
81            sql_mode.push(r#"NO_ENGINE_SUBSTITUTION"#);
82        }
83
84        let mut options = Vec::new();
85        if !sql_mode.is_empty() {
86            options.push(format!(
87                r#"sql_mode=(SELECT CONCAT(@@sql_mode, ',{}'))"#,
88                sql_mode.join(",")
89            ));
90        }
91
92        if let Some(timezone) = &self.timezone {
93            options.push(format!("time_zone={}", quote_string_literal(timezone)));
94        }
95
96        if self.set_names {
97            // As it turns out, we don't _have_ to set a collation if we don't want to.
98            // We can let the server choose the default collation for the charset.
99            let set_names = if let Some(collation) = &self.collation {
100                format!(
101                    "NAMES {} COLLATE {}",
102                    quote_string_literal(&self.charset),
103                    quote_string_literal(collation),
104                )
105            } else {
106                // Leaves the default collation up to the server,
107                // but ensures statements and results are encoded using the proper charset.
108                format!("NAMES {}", quote_string_literal(&self.charset))
109            };
110
111            options.push(set_names);
112        }
113
114        if options.is_empty() {
115            None
116        } else {
117            Some(format!(r#"SET {};"#, options.join(",")))
118        }
119    }
120}
121
122/// Render `value` as a MySQL string literal: wrapped in single quotes with
123/// embedded backslashes and single quotes escaped.
124///
125/// `charset`, `collation` and `time_zone` are taken from the connection URL
126/// (or the builder methods) and used to be interpolated into the connect-time
127/// `SET` statement without quoting, so a crafted value could break out of the
128/// statement and inject arbitrary SQL. Quoting them as string literals closes
129/// that hole.
130///
131/// Doubling single quotes is safe regardless of the `NO_BACKSLASH_ESCAPES`
132/// sql mode; backslashes are escaped as well so one cannot combine with a
133/// following quote into an escape sequence.
134fn quote_string_literal(value: &str) -> String {
135    let mut quoted = String::with_capacity(value.len() + 2);
136    quoted.push('\'');
137    for ch in value.chars() {
138        match ch {
139            '\\' => quoted.push_str(r#"\\"#),
140            '\'' => quoted.push_str("''"),
141            _ => quoted.push(ch),
142        }
143    }
144    quoted.push('\'');
145    quoted
146}
147
148#[cfg(test)]
149mod tests {
150    use super::*;
151    use crate::MySqlConnectOptions;
152    use std::str::FromStr;
153
154    fn statement_for(url: &str) -> String {
155        MySqlConnectOptions::from_str(url)
156            .expect("valid URL")
157            .connect_init_statement()
158            .expect("connect-time SET statement")
159    }
160
161    #[test]
162    fn init_statement_quotes_charset_and_collation() {
163        let stmt = statement_for("mysql://user:password@localhost/database");
164
165        // Defaults (`pipes_as_concat`, `no_engine_substitution`, `+00:00`,
166        // `utf8mb4`) are preserved; `NAMES` charset is quoted as a string literal.
167        assert_eq!(
168            stmt,
169            "SET sql_mode=(SELECT CONCAT(@@sql_mode, ',PIPES_AS_CONCAT,NO_ENGINE_SUBSTITUTION')),\
170             time_zone='+00:00',NAMES 'utf8mb4';"
171        );
172    }
173
174    #[test]
175    fn init_statement_quotes_time_zone() {
176        let stmt = statement_for("mysql://user:password@localhost/database?timezone=%2B08:00");
177
178        assert!(
179            stmt.contains("time_zone='+08:00'"),
180            "unexpected statement: {stmt}"
181        );
182    }
183
184    #[test]
185    fn init_statement_quotes_explicit_collation() {
186        let stmt = statement_for("mysql://user:password@localhost/database?collation=utf8mb4_bin");
187
188        assert!(
189            stmt.contains("NAMES 'utf8mb4' COLLATE 'utf8mb4_bin'"),
190            "unexpected statement: {stmt}"
191        );
192    }
193
194    #[test]
195    fn init_statement_neutralizes_time_zone_injection() {
196        // `time_zone` used to be interpolated into `'...'` without escaping,
197        // so a quote in the value could terminate the literal and start a new
198        // statement (the connection enables CLIENT_MULTI_STATEMENTS).
199        let stmt = statement_for(
200            "mysql://user:password@localhost/database?timezone=%27%3BSELECT+SLEEP%285%29%3B--%20",
201        );
202
203        // The raw quote must not appear unescaped...
204        assert!(
205            !stmt.contains("time_zone='';"),
206            "injection not neutralized: {stmt}"
207        );
208        // ...instead the quote is doubled inside the literal.
209        assert!(
210            stmt.contains("time_zone=''';SELECT SLEEP(5);-- '"),
211            "unexpected statement: {stmt}"
212        );
213    }
214
215    #[test]
216    fn init_statement_neutralizes_charset_injection() {
217        // `charset` used to be interpolated with no quoting at all.
218        let stmt = statement_for(
219            "mysql://user:password@localhost/database?charset=utf8mb4%27%3BSELECT+SLEEP%285%29%3B--%20",
220        );
221
222        assert!(
223            stmt.contains("NAMES 'utf8mb4'';SELECT SLEEP(5);-- '"),
224            "unexpected statement: {stmt}"
225        );
226    }
227
228    #[test]
229    fn init_statement_neutralizes_collation_injection() {
230        let stmt = statement_for(
231            "mysql://user:password@localhost/database?collation=x%27%3BSELECT+SLEEP%285%29%3B--%20",
232        );
233
234        assert!(
235            stmt.contains("COLLATE 'x'';SELECT SLEEP(5);-- '"),
236            "unexpected statement: {stmt}"
237        );
238    }
239
240    #[test]
241    fn init_statement_escapes_backslashes() {
242        // A backslash must not be able to combine with the doubled quote
243        // into an escape sequence that re-opens injection.
244        assert_eq!(quote_string_literal("a\\b"), "'a\\\\b'");
245        assert_eq!(quote_string_literal("a\\'b"), "'a\\\\''b'");
246        assert_eq!(quote_string_literal("plain"), "'plain'");
247        assert_eq!(quote_string_literal("it's"), "'it''s'");
248    }
249}