This is an automated email from the ASF dual-hosted git repository. Xuanwo pushed a commit to branch xuanwo/fix-mysql-sql-quoting-and-list-collation in repository https://gitbox.apache.org/repos/asf/opendal.git
commit 541601ee50c21f4d8fbbe5e5c0b1c146d30f7026 Author: Xuanwo <[email protected]> AuthorDate: Tue Nov 24 01:24:47 2026 +0100 fix(services/mysql): escape SQL identifiers, enforce binary list matching with NO_BACKSLASH_ESCAPES safety, and validate config --- core/services/mysql/src/backend.rs | 99 ++++++++++++++++++++---- core/services/mysql/src/config.rs | 108 +++++++++++++++++++++++++- core/services/mysql/src/core.rs | 130 +++++++++++++++++++------------- core/services/mysql/src/lister.rs | 150 ++++++++++++++++++++++++++++++++----- 4 files changed, 402 insertions(+), 85 deletions(-) diff --git a/core/services/mysql/src/backend.rs b/core/services/mysql/src/backend.rs index 102dfd4392..1cb751e598 100644 --- a/core/services/mysql/src/backend.rs +++ b/core/services/mysql/src/backend.rs @@ -18,7 +18,6 @@ use std::fmt::Debug; use std::sync::Arc; -use asyncband::once::OnceCell; use sqlx::mysql::MySqlConnectOptions; use super::MYSQL_SCHEME; @@ -102,13 +101,30 @@ impl MysqlBuilder { } } +fn validate_identifier(name: &str, value: &str) -> Result<()> { + if value.is_empty() { + return Err( + Error::new(ErrorKind::ConfigInvalid, format!("{name} is empty")) + .with_context("service", MYSQL_SCHEME), + ); + } + if value.contains('\0') { + return Err(Error::new( + ErrorKind::ConfigInvalid, + format!("{name} must not contain NUL bytes"), + ) + .with_context("service", MYSQL_SCHEME)); + } + Ok(()) +} + impl Builder for MysqlBuilder { type Config = MysqlConfig; fn build(self) -> Result<impl Service> { let conn = match self.config.connection_string { - Some(v) => v, - None => { + Some(v) if !v.is_empty() => v, + _ => { return Err( Error::new(ErrorKind::ConfigInvalid, "connection_string is empty") .with_context("service", MYSQL_SCHEME), @@ -129,24 +145,21 @@ impl Builder for MysqlBuilder { .with_context("service", MYSQL_SCHEME)); } }; + validate_identifier("table", &table)?; let key_field = self.config.key_field.unwrap_or_else(|| "key".to_string()); + validate_identifier("key_field", &key_field)?; let value_field = self .config .value_field .unwrap_or_else(|| "value".to_string()); + validate_identifier("value_field", &value_field)?; let root = normalize_root(self.config.root.unwrap_or_else(|| "/".to_string()).as_str()); - Ok(MysqlBackend::new(MysqlCore { - pool: OnceCell::new(), - config, - table, - key_field, - value_field, - }) - .with_normalized_root(root)) + let core = MysqlCore::new(config, &table, &key_field, &value_field); + Ok(MysqlBackend::new(core, &table).with_normalized_root(root)) } } @@ -160,8 +173,8 @@ pub struct MysqlBackend { } impl MysqlBackend { - pub fn new(core: MysqlCore) -> Self { - let info = ServiceInfo::new(MYSQL_SCHEME, "/", &core.table); + pub fn new(core: MysqlCore, table: &str) -> Self { + let info = ServiceInfo::new(MYSQL_SCHEME, "/", table); let capability = Capability { read: true, list: true, @@ -313,3 +326,63 @@ impl Service for MysqlBackend { )) } } + +#[cfg(test)] +mod tests { + use super::*; + + fn valid_config() -> MysqlConfig { + MysqlConfig { + connection_string: Some("mysql://root:[email protected]:3306/testdb".to_string()), + table: Some("data".to_string()), + ..Default::default() + } + } + + #[test] + fn build_rejects_empty_and_nul_identifiers() { + for config in [ + MysqlConfig { + connection_string: Some(String::new()), + ..valid_config() + }, + MysqlConfig { + table: Some(String::new()), + ..valid_config() + }, + MysqlConfig { + key_field: Some(String::new()), + ..valid_config() + }, + MysqlConfig { + value_field: Some(String::new()), + ..valid_config() + }, + MysqlConfig { + table: Some("data\0bad".to_string()), + ..valid_config() + }, + MysqlConfig { + key_field: Some("key\0bad".to_string()), + ..valid_config() + }, + MysqlConfig { + value_field: Some("val\0bad".to_string()), + ..valid_config() + }, + ] { + let err = config.into_builder().build().unwrap_err(); + assert_eq!(err.kind(), ErrorKind::ConfigInvalid); + } + } + + #[test] + fn build_preserves_unquoted_table_name_in_service_info() { + let config = MysqlConfig { + table: Some("my`table".to_string()), + ..valid_config() + }; + let service = config.into_builder().build().unwrap(); + assert_eq!(service.info().name().as_ref(), "my`table"); + } +} diff --git a/core/services/mysql/src/config.rs b/core/services/mysql/src/config.rs index 25b807a5db..8818d4f20b 100644 --- a/core/services/mysql/src/config.rs +++ b/core/services/mysql/src/config.rs @@ -61,6 +61,37 @@ impl Debug for MysqlConfig { } } +fn percent_encode_userinfo(input: &str) -> String { + use std::fmt::Write; + + let mut encoded = String::with_capacity(input.len()); + for byte in input.bytes() { + if byte.is_ascii_alphanumeric() || matches!(byte, b'-' | b'.' | b'_' | b'~') { + encoded.push(byte as char); + } else { + let _ = write!(encoded, "%{byte:02X}"); + } + } + encoded +} + +fn format_connection_string( + authority: &str, + username: Option<&str>, + password: Option<&str>, +) -> String { + match (username, password) { + (Some(user), Some(pass)) => format!( + "mysql://{}:{}@{authority}", + percent_encode_userinfo(user), + percent_encode_userinfo(pass) + ), + (Some(user), None) => format!("mysql://{}@{authority}", percent_encode_userinfo(user)), + (None, Some(pass)) => format!("mysql://:{}@{authority}", percent_encode_userinfo(pass)), + (None, None) => format!("mysql://{authority}"), + } +} + impl opendal_core::Configurator for MysqlConfig { type Builder = MysqlBuilder; @@ -69,7 +100,9 @@ impl opendal_core::Configurator for MysqlConfig { if let Some(authority) = uri.authority() { map.entry("connection_string".to_string()) - .or_insert_with(|| format!("mysql://{authority}")); + .or_insert_with(|| { + format_connection_string(authority, uri.username(), uri.password()) + }); } if let Some(path) = uri.root() @@ -88,7 +121,8 @@ impl opendal_core::Configurator for MysqlConfig { if let Some(root) = rest && !root.is_empty() { - map.insert("root".to_string(), root.to_string()); + map.entry("root".to_string()) + .or_insert_with(|| root.to_string()); } } @@ -103,6 +137,7 @@ impl opendal_core::Configurator for MysqlConfig { #[cfg(test)] mod tests { use super::*; + use opendal_core::Builder; use opendal_core::Configurator; use opendal_core::OperatorUri; @@ -135,4 +170,73 @@ mod tests { assert_eq!(cfg.table.as_deref(), Some("users")); assert_eq!(cfg.root.as_deref(), Some("logs")); } + + #[test] + fn from_uri_preserves_credentials_and_builds() { + let uri = OperatorUri::new( + "mysql://alice%40corp.com:p%3aa%23s%2fs%40%[email protected]:3306/kv/cache", + Vec::<(String, String)>::new(), + ) + .unwrap(); + + let cfg = MysqlConfig::from_uri(&uri).unwrap(); + assert_eq!( + cfg.connection_string.as_deref(), + Some("mysql://alice%40corp.com:p%3aa%23s%2fs%40%[email protected]:3306") + ); + assert_eq!(cfg.table.as_deref(), Some("kv")); + assert_eq!(cfg.root.as_deref(), Some("cache")); + cfg.into_builder().build().unwrap(); + + let user_only = + OperatorUri::new("mysql://root@[::1]:3306/kv", Vec::<(String, String)>::new()).unwrap(); + let cfg = MysqlConfig::from_uri(&user_only).unwrap(); + assert_eq!( + cfg.connection_string.as_deref(), + Some("mysql://root@[::1]:3306") + ); + cfg.into_builder().build().unwrap(); + + let pass_only = OperatorUri::new( + "mysql://:s%23e%[email protected]:3306/kv", + Vec::<(String, String)>::new(), + ) + .unwrap(); + let cfg = MysqlConfig::from_uri(&pass_only).unwrap(); + assert_eq!( + cfg.connection_string.as_deref(), + Some("mysql://:s%23e%[email protected]:3306") + ); + cfg.into_builder().build().unwrap(); + } + + #[test] + fn from_uri_respects_explicit_root_and_connection_string_options() { + let uri = OperatorUri::new( + "mysql://user:[email protected]:3306/kv/path?root=override", + Vec::<(String, String)>::new(), + ) + .unwrap(); + let cfg = MysqlConfig::from_uri(&uri).unwrap(); + assert_eq!( + cfg.connection_string.as_deref(), + Some("mysql://user:[email protected]:3306") + ); + assert_eq!(cfg.table.as_deref(), Some("kv")); + assert_eq!(cfg.root.as_deref(), Some("override")); + + let explicit_conn = OperatorUri::new( + "mysql://user:[email protected]:3306/kv/path", + [( + "connection_string".to_string(), + "mysql://other:[email protected]:3306/testdb".to_string(), + )], + ) + .unwrap(); + let cfg = MysqlConfig::from_uri(&explicit_conn).unwrap(); + assert_eq!( + cfg.connection_string.as_deref(), + Some("mysql://other:[email protected]:3306/testdb") + ); + } } diff --git a/core/services/mysql/src/core.rs b/core/services/mysql/src/core.rs index d16cd6c969..6d165f44c7 100644 --- a/core/services/mysql/src/core.rs +++ b/core/services/mysql/src/core.rs @@ -23,15 +23,30 @@ use opendal_core::*; #[derive(Clone, Debug)] pub struct MysqlCore { - pub pool: OnceCell<MySqlPool>, - pub config: MySqlConnectOptions, + pool: OnceCell<MySqlPool>, + config: MySqlConnectOptions, - pub table: String, - pub key_field: String, - pub value_field: String, + table: String, + key_field: String, + value_field: String, } impl MysqlCore { + pub fn new( + config: MySqlConnectOptions, + table: &str, + key_field: &str, + value_field: &str, + ) -> Self { + Self { + pool: OnceCell::new(), + config, + table: quote_identifier(table), + key_field: quote_identifier(key_field), + value_field: quote_identifier(value_field), + } + } + async fn get_client(&self) -> Result<&MySqlPool> { self.pool .get_or_try_init(|| async { @@ -45,19 +60,11 @@ impl MysqlCore { pub async fn get(&self, path: &str) -> Result<Option<Buffer>> { let pool = self.get_client().await?; - // MySQL uses a backtick for identifier quote. An identifier may or may not be case-sensitive, - // depending on database configuration. Only a quoted identifier can have special characters. - // Read more: - // https://dev.mysql.com/doc/refman/9.7/en/identifiers.html - // https://dev.mysql.com/doc/refman/9.7/en/identifier-case-sensitivity.html - // - // We use: - // - formatted, quoted identifiers for trusted table and field configuration - // - bind parameters for values to avoid malformed SQL and SQL injection - // to ensure correctness. `AssertSqlSafe` records this audit for sqlx. + let table = &self.table; + let key_field = &self.key_field; + let value_field = &self.value_field; let value: Option<Vec<u8>> = sqlx::query_scalar(sqlx::AssertSqlSafe(format!( - "SELECT `{}` FROM `{}` WHERE `{}` = ? LIMIT 1", - self.value_field, self.table, self.key_field + "SELECT {value_field} FROM {table} WHERE {key_field} = ? LIMIT 1", ))) .bind(path) .fetch_optional(pool) @@ -70,9 +77,11 @@ impl MysqlCore { pub async fn get_length(&self, path: &str) -> Result<Option<usize>> { let pool = self.get_client().await?; + let table = &self.table; + let key_field = &self.key_field; + let value_field = &self.value_field; let value: Option<i64> = sqlx::query_scalar(sqlx::AssertSqlSafe(format!( - "SELECT OCTET_LENGTH(`{}`) FROM `{}` WHERE `{}` = ? LIMIT 1", - self.value_field, self.table, self.key_field + "SELECT OCTET_LENGTH({value_field}) FROM {table} WHERE {key_field} = ? LIMIT 1", ))) .bind(path) .fetch_optional(pool) @@ -92,10 +101,12 @@ impl MysqlCore { pub async fn set(&self, path: &str, value: Buffer) -> Result<()> { let pool = self.get_client().await?; + let table = &self.table; + let key_field = &self.key_field; + let value_field = &self.value_field; sqlx::query(sqlx::AssertSqlSafe(format!( - r#"INSERT INTO `{}` (`{}`, `{}`) VALUES (?, ?) - ON DUPLICATE KEY UPDATE `{}` = VALUES(`{}`)"#, - self.table, self.key_field, self.value_field, self.value_field, self.value_field + "INSERT INTO {table} ({key_field}, {value_field}) VALUES (?, ?) + ON DUPLICATE KEY UPDATE {value_field} = VALUES({value_field})", ))) .bind(path) .bind(value.to_vec()) @@ -109,9 +120,10 @@ impl MysqlCore { pub async fn delete(&self, path: &str) -> Result<()> { let pool = self.get_client().await?; + let table = &self.table; + let key_field = &self.key_field; sqlx::query(sqlx::AssertSqlSafe(format!( - "DELETE FROM `{}` WHERE `{}` = ?", - self.table, self.key_field + "DELETE FROM {table} WHERE {key_field} = ?", ))) .bind(path) .execute(pool) @@ -124,31 +136,40 @@ impl MysqlCore { pub async fn list(&self, path: &str) -> Result<Vec<String>> { let pool = self.get_client().await?; - let mut sql = format!( - "SELECT `{}` FROM `{}` WHERE `{}` LIKE ?", - self.key_field, self.table, self.key_field - ); - sql.push_str(&format!(" ORDER BY `{}`", self.key_field)); - - let escaped = escape_like(path); - sqlx::query_scalar(sqlx::AssertSqlSafe(sql)) - .bind(format!("{escaped}%")) - .fetch_all(pool) - .await - .map_err(parse_mysql_error) + let table = &self.table; + let key_field = &self.key_field; + // Keep the raw LIKE predicate so MySQL can use a B-tree range scan on + // `key_field`, then enforce exact UTF-8 codepoint prefix matching via + // `utf8mb4_bin` regardless of the column's collation. Use a non-backslash + // escape character so escaping works identically under `NO_BACKSLASH_ESCAPES`. + let pattern = format!("{}%", escape_like(path)); + sqlx::query_scalar(sqlx::AssertSqlSafe(format!( + "SELECT {key_field} FROM {table} \ + WHERE {key_field} LIKE ? ESCAPE '!' \ + AND CONVERT({key_field} USING utf8mb4) COLLATE utf8mb4_bin \ + LIKE CONVERT(? USING utf8mb4) COLLATE utf8mb4_bin ESCAPE '!' \ + ORDER BY {key_field}", + ))) + .bind(&pattern) + .bind(&pattern) + .fetch_all(pool) + .await + .map_err(parse_mysql_error) } } +// MySQL escapes backticks in identifiers by doubling them. Queries +// interpolate only these quoted identifiers and bind paths and values. +fn quote_identifier(identifier: &str) -> String { + format!("`{}`", identifier.replace('`', "``")) +} + fn escape_like(s: &str) -> String { - const ESCAPE_CHAR: char = '\\'; + const ESCAPE_CHAR: char = '!'; let mut out = String::with_capacity(s.len()); for ch in s.chars() { match ch { - c if c == ESCAPE_CHAR => { - out.push(ESCAPE_CHAR); - out.push(ESCAPE_CHAR); - } - '%' | '_' => { + '!' | '%' | '_' => { out.push(ESCAPE_CHAR); out.push(ch); } @@ -164,7 +185,15 @@ fn parse_mysql_error(err: sqlx::Error) -> Error { #[cfg(test)] mod tests { - use crate::core::escape_like; + use super::*; + + #[test] + fn test_quote_identifier() { + assert_eq!(quote_identifier("data"), "`data`"); + assert_eq!(quote_identifier("my`table"), "`my``table`"); + assert_eq!(quote_identifier("k` OR 1=1 -- "), "`k`` OR 1=1 -- `"); + assert_eq!(quote_identifier("a``b"), "`a````b`"); + } #[test] fn test_escape_like_basic() { @@ -174,21 +203,22 @@ mod tests { #[test] fn test_escape_like_wildcards() { - assert_eq!(escape_like("%"), r"\%"); - assert_eq!(escape_like("_"), r"\_"); - assert_eq!(escape_like("a%b_c"), r"a\%b\_c"); + assert_eq!(escape_like("%"), "!%"); + assert_eq!(escape_like("_"), "!_"); + assert_eq!(escape_like("a%b_c"), "a!%b!_c"); } #[test] fn test_escape_like_escape_char() { - assert_eq!(escape_like(r"\"), r"\\"); - assert_eq!(escape_like(r"\%"), r"\\\%"); + assert_eq!(escape_like("!"), "!!"); + assert_eq!(escape_like("!%"), "!!!%"); + assert_eq!(escape_like(r"\"), r"\"); } #[test] fn test_escape_like_mixed() { - let input = r"foo\%bar_baz%"; - let expected = r"foo\\\%bar\_baz\%"; + let input = r"foo\%bar_baz!%"; + let expected = r"foo\!%bar!_baz!!!%"; assert_eq!(escape_like(input), expected); } diff --git a/core/services/mysql/src/lister.rs b/core/services/mysql/src/lister.rs index 55edc0cf8a..6f8eb61c6a 100644 --- a/core/services/mysql/src/lister.rs +++ b/core/services/mysql/src/lister.rs @@ -21,41 +21,54 @@ use std::vec::IntoIter; use opendal_core::MetadataBuilder; use opendal_core::Result; use opendal_core::raw::oio::{Entry, List}; -use opendal_core::raw::{build_absolute_path, build_relative_path}; +use opendal_core::raw::{build_absolute_path, normalize_path}; use super::core::MysqlCore; pub struct MysqlLister { - root: String, + root_prefix: String, + prefix: String, entries: IntoIter<String>, } impl MysqlLister { pub async fn new(core: Arc<MysqlCore>, root: String, path: String) -> Result<Self> { - let entries = core - .list(&build_absolute_path(&root, &path)) - .await? - .into_iter(); - Ok(Self { root, entries }) + let prefix = build_absolute_path(&root, &path); + let entries = core.list(&prefix).await?; + Ok(Self::from_entries(&root, prefix, entries)) + } + + fn from_entries(root: &str, prefix: String, entries: Vec<String>) -> Self { + Self { + root_prefix: build_absolute_path(root, "/"), + prefix, + entries: entries.into_iter(), + } } } impl List for MysqlLister { async fn next(&mut self) -> Result<Option<Entry>> { - let Some(key) = self.entries.next() else { - return Ok(None); - }; - - let mut path = build_relative_path(&self.root, &key); - if path.is_empty() { - path = "/".to_string(); + for key in self.entries.by_ref() { + if !key.starts_with(&self.prefix) { + continue; + } + let Some(rel) = key.strip_prefix(&self.root_prefix) else { + continue; + }; + // Ignore external keys that OpenDAL cannot address by their exact path. + if !rel.is_empty() && (rel == "/" || normalize_path(rel) != rel) { + continue; + } + let path = if rel.is_empty() { "/" } else { rel }; + let meta = if path.ends_with('/') { + MetadataBuilder::dir() + } else { + MetadataBuilder::unknown() + }; + return Ok(Some(Entry::new(path, meta.build()))); } - let meta = if path.ends_with('/') { - MetadataBuilder::dir() - } else { - MetadataBuilder::unknown() - }; - Ok(Some(Entry::new(&path, meta.build()))) + Ok(None) } } @@ -92,3 +105,100 @@ impl List for MysqlLazyLister { .await } } + +#[cfg(test)] +mod tests { + use super::*; + use opendal_core::EntryMode; + + async fn collect(mut lister: MysqlLister) -> Vec<(String, EntryMode)> { + let mut out = Vec::new(); + while let Some(entry) = lister.next().await.unwrap() { + out.push((entry.path().to_string(), entry.metadata().mode())); + } + out + } + + #[tokio::test] + async fn lister_skips_cross_root_and_shorter_non_matching_keys() { + let lister = MysqlLister::from_entries( + "/App/", + "App/".to_string(), + vec![ + "app/secret.txt".to_string(), + "App/".to_string(), + "App/public.txt".to_string(), + "App/dir/".to_string(), + ], + ); + + assert_eq!( + collect(lister).await, + vec![ + ("/".to_string(), EntryMode::DIR), + ("public.txt".to_string(), EntryMode::Unknown), + ("dir/".to_string(), EntryMode::DIR), + ] + ); + } + + #[tokio::test] + async fn lister_does_not_panic_on_byte_length_mismatched_keys() { + // Under accent-insensitive collations, `"é/"` (3 bytes) can match a + // 4-byte decomposed prefix `"e\u{0301}/"`, and `"e/"` (2 bytes) can + // match a 3-byte prefix `"é/"`. + let decomposed = MysqlLister::from_entries( + "/e\u{0301}/", + "e\u{0301}/".to_string(), + vec!["é/".to_string(), "e\u{0301}/ok.txt".to_string()], + ); + assert_eq!( + collect(decomposed).await, + vec![("ok.txt".to_string(), EntryMode::Unknown)] + ); + + let accented = MysqlLister::from_entries( + "/é/", + "é/".to_string(), + vec!["e/".to_string(), "é/ok.txt".to_string()], + ); + assert_eq!( + collect(accented).await, + vec![("ok.txt".to_string(), EntryMode::Unknown)] + ); + } + + #[tokio::test] + async fn lister_enforces_exact_prefix_and_skips_non_normalized_keys() { + let lister = MysqlLister::from_entries( + "/", + "Dir/".to_string(), + vec![ + "dir/b".to_string(), + "Dir/a".to_string(), + "Dir//bad".to_string(), + ], + ); + assert_eq!( + collect(lister).await, + vec![("Dir/a".to_string(), EntryMode::Unknown)] + ); + + let root_lister = MysqlLister::from_entries( + "/", + String::new(), + vec![ + String::new(), + "/external".to_string(), + "file.txt".to_string(), + ], + ); + assert_eq!( + collect(root_lister).await, + vec![ + ("/".to_string(), EntryMode::DIR), + ("file.txt".to_string(), EntryMode::Unknown), + ] + ); + } +}
