ch-database 0.1.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),
}

/// 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 Some(last_at) = authority.rfind('@') else {
        return Ok(raw.to_string());
    };

    let (credentials, host) = authority.split_at(last_at);
    let host = &host[1..];

    let Some((username, password)) = credentials.split_once(':') else {
        return Ok(raw.to_string());
    };

    if !password_needs_encoding(password) {
        return Ok(raw.to_string());
    }

    let encoded_password = encode_password(password);
    let normalized = format!("{scheme}://{username}:{encoded_password}@{host}{tail}");

    Url::parse(&normalized)
        .map(|_| normalized)
        .map_err(MySqlUrlError::InvalidUrl)
}

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

        if let Some(at_offset) = redacted[credentials_start..].find('@') {
            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 password_needs_encoding(password: &str) -> bool {
    let bytes = password.as_bytes();
    let mut index = 0;

    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()
            {
                return true;
            }
            index += 3;
            continue;
        }

        let ch = password[index..]
            .chars()
            .next()
            .expect("iterator guarantees at least one character");

        if !is_userinfo_char(ch) {
            return true;
        }

        index += ch.len_utf8();
    }

    false
}

fn is_userinfo_char(ch: char) -> bool {
    ch.is_ascii_alphanumeric()
        || matches!(
            ch,
            '-' | '.'
                | '_'
                | '~'
                | '!'
                | '$'
                | '&'
                | '\''
                | '('
                | ')'
                | '*'
                | '+'
                | ','
                | ';'
                | '='
                | ':'
        )
}

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 ch = password[index..]
            .chars()
            .next()
            .expect("iterator guarantees at least one character");

        let ch_len = ch.len_utf8();
        if is_userinfo_char(ch) {
            encoded.push(ch);
        } else {
            let mut buf = [0u8; 4];
            for byte in ch.encode_utf8(&mut buf).as_bytes() {
                push_pct_encoded(&mut encoded, *byte);
            }
        }

        index += ch_len;
    }

    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"));
    }
}