ch-database 0.2.1

Database and object storage primitives for SQLx, SpacetimeDB, and S3
Documentation
use thiserror::Error;
use url::Url;

/// Errors returned while normalizing a MariaDB/MySQL connection URL.
#[derive(Debug, Error)]
pub enum MySqlUrlError {
    /// The value is not a MySQL URL.
    #[error("connection URL must use the mysql scheme")]
    InvalidScheme,
    /// The URL does not contain a database path.
    #[error("connection URL must include a database name")]
    MissingDatabase,
    /// The normalized URL is not syntactically valid.
    #[error("connection URL is invalid")]
    InvalidUrl(#[source] url::ParseError),
}

/// Validates a MySQL URL and percent-encodes its password using the URL parser.
///
/// Existing percent escapes are preserved. New connections can pass a valid URL
/// directly to [`super::pool::connect_mysql_pool`], or use SQLx connect options
/// when credentials are available as separate values.
pub fn normalize_mysql_url(raw: &str) -> Result<String, MySqlUrlError> {
    let Some(("mysql", remainder)) = raw.split_once("://") else {
        return Err(MySqlUrlError::InvalidScheme);
    };
    let (authority, path) = remainder
        .split_once('/')
        .ok_or(MySqlUrlError::MissingDatabase)?;
    let Some((credentials, host)) = authority.rsplit_once('@') else {
        return parse_mysql_url(raw).map(String::from);
    };
    let Some((username, password)) = credentials.split_once(':') else {
        return parse_mysql_url(raw).map(String::from);
    };

    // Set the raw password after parsing so URL parsing cannot strip its tabs or newlines.
    let mut parsed = parse_mysql_url(&format!("mysql://{username}@{host}/{path}"))?;
    let mut encoded = String::with_capacity(password.len());
    let mut start = 0;
    for (index, _) in password.match_indices('%') {
        encoded.push_str(&password[start..index + 1]);
        if !password
            .as_bytes()
            .get(index + 1..index + 3)
            .is_some_and(|digits| digits.iter().all(u8::is_ascii_hexdigit))
        {
            encoded.push_str("25");
        }
        start = index + 1;
    }
    encoded.push_str(&password[start..]);
    parsed
        .set_password(Some(&encoded))
        .map_err(|()| MySqlUrlError::InvalidUrl(url::ParseError::EmptyHost))?;
    Ok(parsed.into())
}

pub(crate) fn parse_mysql_url(raw: &str) -> Result<Url, MySqlUrlError> {
    if !raw.starts_with("mysql://") {
        return Err(MySqlUrlError::InvalidScheme);
    }
    let parsed = Url::parse(raw).map_err(MySqlUrlError::InvalidUrl)?;
    if parsed.path().trim_start_matches('/').is_empty() {
        return Err(MySqlUrlError::MissingDatabase);
    }
    if parsed.host_str().is_none_or(str::is_empty) {
        return Err(MySqlUrlError::InvalidUrl(url::ParseError::EmptyHost));
    }
    Ok(parsed)
}

/// Redacts the password portion of a MySQL URL for logging.
pub fn redact_mysql_url(url: &str) -> String {
    const REDACTED: &str = "****";

    let mut redacted = url.to_string();

    if let Some(scheme_end) = redacted.find("://") {
        let credentials_start = scheme_end + 3;

        let authority_end = redacted[credentials_start..]
            .find('/')
            .map_or(redacted.len(), |offset| credentials_start + offset);
        if let Some(at_offset) = redacted[credentials_start..authority_end].rfind('@') {
            let at_index = credentials_start + at_offset;

            if let Some(colon_offset) = redacted[credentials_start..at_index].find(':') {
                let colon_index = credentials_start + colon_offset;
                redacted.replace_range(colon_index + 1..at_index, REDACTED);
            }
        }
    }

    redacted
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn redacts_password_in_mysql_url() {
        let url = "mysql://user:secret@127.0.0.1:4520/db";
        assert_eq!(redact_mysql_url(url), "mysql://user:****@127.0.0.1:4520/db");
    }

    #[test]
    fn normalizes_password_with_reserved_chars() {
        let url = "mysql://user:p@ss word@127.0.0.1:4520/db";
        let normalized = normalize_mysql_url(url).expect("url should normalize");
        assert!(normalized.contains("mysql://user:p%40ss%20word@127.0.0.1:4520/db"));
    }

    #[test]
    fn redacts_the_entire_password_with_embedded_at_signs() {
        assert_eq!(
            redact_mysql_url("mysql://user:p@ss@localhost/db"),
            "mysql://user:****@localhost/db"
        );
        assert_eq!(
            redact_mysql_url("mysql://localhost:3306/db?label=a@b"),
            "mysql://localhost:3306/db?label=a@b"
        );
    }

    #[test]
    fn validates_urls_even_when_no_password_encoding_is_needed() {
        for raw in [
            "mysql://[invalid/db",
            "mysql:///db",
            "mysql://host:invalid/db",
        ] {
            assert!(
                matches!(normalize_mysql_url(raw), Err(MySqlUrlError::InvalidUrl(_))),
                "{raw}"
            );
        }
        for raw in ["mysql://host", "mysql://host/", "mysql://host/?option=1"] {
            assert!(
                matches!(
                    normalize_mysql_url(raw),
                    Err(MySqlUrlError::MissingDatabase)
                ),
                "{raw}"
            );
        }
    }

    #[test]
    fn encoding_is_idempotent_for_unicode_and_percent_sequences() {
        let normalized = normalize_mysql_url("mysql://user:päss%20%zz@host/db").unwrap();
        assert_eq!(normalized, "mysql://user:p%C3%A4ss%20%25zz@host/db");
        assert_eq!(normalize_mysql_url(&normalized).unwrap(), normalized);
    }

    #[test]
    fn normalization_preserves_literal_password_controls_and_escaped_delimiters() {
        let normalized = normalize_mysql_url("mysql://user:p\t\na%2Fb%3Fc%23d@host/db").unwrap();
        assert_eq!(normalized, "mysql://user:p%09%0Aa%2Fb%3Fc%23d@host/db");
        assert_eq!(normalize_mysql_url(&normalized).unwrap(), normalized);
    }
}