ch-database 0.2.0

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),
}

/// Ensures MySQL URLs remain parseable even when passwords contain characters that require encoding.
///
/// SQLx accepts a URL string, but passwords containing non-userinfo characters can invalidate the
/// URI. This helper percent-encodes the password portion when needed, leaving already encoded
/// sequences intact.
pub fn normalize_mysql_url(raw: &str) -> Result<String, MySqlUrlError> {
    let Some((scheme, remainder)) = raw.split_once("://") else {
        return Err(MySqlUrlError::InvalidScheme);
    };

    if scheme != "mysql" {
        return Err(MySqlUrlError::InvalidScheme);
    }

    let slash_index = remainder.find('/').ok_or(MySqlUrlError::MissingDatabase)?;
    if remainder[slash_index + 1..]
        .split(['?', '#'])
        .next()
        .is_none_or(str::is_empty)
    {
        return Err(MySqlUrlError::MissingDatabase);
    }
    let (authority, tail) = remainder.split_at(slash_index);

    let normalized = match authority.rsplit_once('@') {
        Some((credentials, host)) => match credentials.split_once(':') {
            Some((username, password)) => {
                let password = encode_password(password);
                format!("{scheme}://{username}:{password}@{host}{tail}")
            }
            None => raw.to_owned(),
        },
        None => raw.to_owned(),
    };

    let parsed = Url::parse(&normalized).map_err(MySqlUrlError::InvalidUrl)?;
    if parsed.host_str().is_none_or(str::is_empty) {
        return Err(MySqlUrlError::InvalidUrl(url::ParseError::EmptyHost));
    }
    Ok(normalized)
}

/// 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
}

fn is_userinfo_byte(byte: u8) -> bool {
    byte.is_ascii_alphanumeric()
        || matches!(
            byte,
            b'-' | b'.'
                | b'_'
                | b'~'
                | b'!'
                | b'$'
                | b'&'
                | b'\''
                | b'('
                | b')'
                | b'*'
                | b'+'
                | b','
                | b';'
                | b'='
                | b':'
        )
}

fn encode_password(password: &str) -> String {
    let mut encoded = String::with_capacity(password.len());
    let mut index = 0;
    let bytes = password.as_bytes();

    while index < bytes.len() {
        if bytes[index] == b'%' {
            if index + 2 < bytes.len()
                && bytes[index + 1].is_ascii_hexdigit()
                && bytes[index + 2].is_ascii_hexdigit()
            {
                encoded.push('%');
                encoded.push(bytes[index + 1] as char);
                encoded.push(bytes[index + 2] as char);
                index += 3;
                continue;
            }

            push_pct_encoded(&mut encoded, b'%');
            index += 1;
            continue;
        }

        let byte = bytes[index];
        if is_userinfo_byte(byte) {
            encoded.push(char::from(byte));
        } else {
            push_pct_encoded(&mut encoded, byte);
        }

        index += 1;
    }

    encoded
}

fn push_pct_encoded(buffer: &mut String, byte: u8) {
    const HEX: &[u8; 16] = b"0123456789ABCDEF";
    buffer.push('%');
    buffer.push(HEX[(byte >> 4) as usize] as char);
    buffer.push(HEX[(byte & 0x0F) as usize] as char);
}

#[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);
    }
}