use super::profile::Profile;
use crate::error::{Failure, Result};
use secrecy::SecretString;
use std::path::PathBuf;
const ACCEPTED_SCHEMES: [&str; 2] = ["mariadb", "mysql"];
const REDACTED: &str = "***";
#[derive(Debug)]
pub struct Dsn {
pub profile: Profile,
pub secret: Option<SecretString>,
}
impl Dsn {
pub fn parse(text: &str) -> Result<Self> {
let rest = split_scheme(text)?;
let (authority, path_and_query) = split_once_or_all(rest, '/');
let (credential, endpoint) = split_credential(authority);
let (user, secret) = split_user_and_secret(credential);
let (host, port) = split_host_and_port(endpoint, text)?;
let (database, query) = split_once_or_all(path_and_query, '?');
let mut profile = Profile {
host,
port,
user: user.map(decode),
database: (!database.is_empty()).then(|| decode(database)),
..Profile::named("dsn")
};
apply_parameters(&mut profile, query, text)?;
profile.ensure_reachable()?;
Ok(Self {
profile,
secret: secret.map(|value| SecretString::from(decode(value))),
})
}
}
fn split_scheme(text: &str) -> Result<&str> {
let Some((scheme, rest)) = text.split_once("://") else {
return Err(malformed(text, "the text carries no scheme"));
};
if !ACCEPTED_SCHEMES.contains(&scheme.to_ascii_lowercase().as_str()) {
return Err(malformed(
text,
format!("`{scheme}` is not a scheme this product speaks"),
));
}
Ok(rest)
}
fn split_credential(authority: &str) -> (&str, &str) {
authority
.rsplit_once('@')
.map_or(("", authority), |(credential, endpoint)| {
(credential, endpoint)
})
}
fn split_user_and_secret(credential: &str) -> (Option<&str>, Option<&str>) {
if credential.is_empty() {
return (None, None);
}
credential.split_once(':').map_or_else(
|| (Some(credential), None),
|(user, secret)| (Some(user), Some(secret)),
)
}
fn split_host_and_port(endpoint: &str, text: &str) -> Result<(Option<String>, Option<u16>)> {
if endpoint.is_empty() {
return Ok((None, None));
}
let Some((host, port)) = endpoint.rsplit_once(':') else {
return Ok((Some(decode(endpoint)), None));
};
let parsed = port
.parse::<u16>()
.map_err(|_| malformed(text, format!("`{port}` is not a port number")))?;
Ok((Some(decode(host)), Some(parsed)))
}
fn apply_parameters(profile: &mut Profile, query: &str, text: &str) -> Result<()> {
for pair in query.split('&').filter(|pair| !pair.is_empty()) {
let (key, value) = pair.split_once('=').unwrap_or((pair, ""));
let value = decode(value);
match key.to_ascii_lowercase().as_str() {
"socket" => profile.socket = Some(PathBuf::from(value)),
"database" | "db" => profile.database = Some(value),
"ca" => profile.ca = Some(PathBuf::from(value)),
"client_cert" => profile.client_cert = Some(PathBuf::from(value)),
"client_key" => profile.client_key = Some(PathBuf::from(value)),
"require_tls" => profile.require_tls = Some(is_affirmative(&value)),
"read_only" => profile.read_only = is_affirmative(&value),
"auth" => profile.auth_method = Some(value),
unknown => {
return Err(malformed(
text,
format!("`{unknown}` is not a parameter this product understands"),
))
}
}
}
Ok(())
}
fn is_affirmative(value: &str) -> bool {
matches!(
value.to_ascii_lowercase().as_str(),
"1" | "true" | "yes" | "on" | ""
)
}
fn split_once_or_all(text: &str, separator: char) -> (&str, &str) {
text.split_once(separator)
.map_or((text, ""), |(left, right)| (left, right))
}
fn decode(text: &str) -> String {
let mut out = String::with_capacity(text.len());
let mut bytes = text.bytes().collect::<Vec<_>>().into_iter().peekable();
let mut raw: Vec<u8> = Vec::with_capacity(text.len());
while let Some(byte) = bytes.next() {
if byte == b'%' {
let high = bytes.peek().copied().and_then(hex_value);
if let Some(high) = high {
bytes.next();
let low = bytes.peek().copied().and_then(hex_value);
if let Some(low) = low {
bytes.next();
raw.push(high * 16 + low);
continue;
}
raw.push(b'%');
raw.push(b'0' + high);
continue;
}
}
raw.push(byte);
}
out.push_str(&String::from_utf8_lossy(&raw));
out
}
const fn hex_value(byte: u8) -> Option<u8> {
match byte {
b'0'..=b'9' => Some(byte - b'0'),
b'a'..=b'f' => Some(byte - b'a' + 10),
b'A'..=b'F' => Some(byte - b'A' + 10),
_ => None,
}
}
fn malformed(text: &str, detail: impl Into<String>) -> Failure {
let shown = redact(text);
Failure::config(
"dsn.malformed",
format!("the destination `{shown}` cannot be read"),
)
.with_detail("detail", shown)
.with_hint("write it as scheme://user:secret@host:port/database")
.with_cause(detail.into())
}
#[must_use]
pub fn redact(dsn: &str) -> String {
let Some((scheme, rest)) = dsn.split_once("://") else {
return dsn.to_owned();
};
let Some((credential, after_credential)) = rest.rsplit_once('@') else {
return dsn.to_owned();
};
let (endpoint, tail) = split_once_or_all(after_credential, '/');
let separator = if after_credential.len() > endpoint.len() {
"/"
} else {
""
};
let user = credential
.split_once(':')
.map_or(credential, |(user, _)| user);
let masked = if credential.contains(':') {
format!("{user}:{REDACTED}")
} else {
user.to_owned()
};
format!("{scheme}://{masked}@{endpoint}{separator}{tail}")
}
#[cfg(test)]
mod tests {
use super::*;
use secrecy::ExposeSecret;
#[test]
fn a_full_destination_parses_into_its_parts() {
let dsn = Dsn::parse("mariadb://reader:hunter2@db.example:3307/sales").expect("parses");
assert_eq!(dsn.profile.host.as_deref(), Some("db.example"));
assert_eq!(dsn.profile.port, Some(3307));
assert_eq!(dsn.profile.user.as_deref(), Some("reader"));
assert_eq!(dsn.profile.database.as_deref(), Some("sales"));
assert_eq!(
dsn.secret.as_ref().map(ExposeSecret::expose_secret),
Some("hunter2")
);
}
#[test]
fn an_omitted_port_stays_absent() {
let dsn = Dsn::parse("mysql://reader@db.example/sales").expect("parses");
assert_eq!(dsn.profile.port, None);
assert!(dsn.secret.is_none());
}
#[test]
fn escaped_characters_survive_the_parse() {
let dsn = Dsn::parse("mariadb://reader:a%40b%3Ac@db.example/sales").expect("parses");
assert_eq!(
dsn.secret.as_ref().map(ExposeSecret::expose_secret),
Some("a@b:c")
);
}
#[test]
fn known_parameters_are_applied() {
let dsn = Dsn::parse("mariadb://reader@db.example/sales?require_tls=true&read_only=1")
.expect("parses");
assert_eq!(dsn.profile.require_tls, Some(true));
assert!(dsn.profile.read_only);
}
#[test]
fn an_unknown_parameter_is_refused() {
let failure =
Dsn::parse("mariadb://reader@db.example/sales?charset=utf8").expect_err("must refuse");
assert_eq!(failure.category(), crate::error::Category::Config);
assert_eq!(failure.code(), "dsn.malformed");
}
#[test]
fn a_text_this_product_cannot_read_is_refused() {
for text in [
"db.example/sales",
"postgres://reader@db.example/sales",
"mariadb://reader@db.example:notaport/sales",
] {
let failure = Dsn::parse(text).expect_err("must refuse");
assert_eq!(failure.code(), "dsn.malformed", "accepted `{text}`");
}
}
#[test]
fn a_destination_naming_no_server_is_refused() {
let failure = Dsn::parse("mariadb://reader@/sales").expect_err("must refuse");
assert_eq!(failure.code(), "profile.no_destination");
}
#[test]
fn a_failure_message_never_carries_the_secret() {
let failure =
Dsn::parse("mariadb://reader:hunter2@db.example:x/sales").expect_err("must refuse");
assert!(
!failure.message().contains("hunter2"),
"the secret leaked: {}",
failure.message()
);
assert!(failure.message().contains(REDACTED));
}
#[test]
fn redaction_hides_the_secret_and_keeps_the_rest() {
let redacted = redact("mariadb://reader:hunter2@db.example:3307/sales");
assert_eq!(redacted, "mariadb://reader:***@db.example:3307/sales");
}
#[test]
fn a_secret_carrying_a_separator_is_still_hidden() {
let redacted = redact("mariadb://reader:pa/ss@db.example:3307/sales");
assert!(
!redacted.contains("pa/ss"),
"the secret reached the reader: {redacted}"
);
assert!(
redacted.contains(REDACTED),
"nothing was marked: {redacted}"
);
assert!(
redacted.contains("db.example:3307") && redacted.contains("sales"),
"the parts a reader needs were lost: {redacted}"
);
}
#[test]
fn many_separators_do_not_uncover_the_secret() {
let redacted = redact("mariadb://reader:a/b/c@db.example/sales/main");
assert!(
!redacted.contains("a/b/c"),
"the secret reached the reader: {redacted}"
);
assert_eq!(redacted, "mariadb://reader:***@db.example/sales/main");
}
#[test]
fn a_text_without_a_secret_is_left_alone() {
let text = "mariadb://reader@db.example/sales";
assert_eq!(redact(text), text);
assert_eq!(redact("not a destination"), "not a destination");
}
#[test]
fn redaction_holds_for_every_shape_of_text() {
for text in [
"mariadb://u:s3cr3t@h",
"mariadb://u:s3cr3t@h/db",
"mariadb://u:s3cr3t@h:3306/db?require_tls=1",
"mysql://u:s3cr3t@h:3306/",
] {
let redacted = redact(text);
assert!(
!redacted.contains("s3cr3t"),
"the secret leaked from `{text}`"
);
assert!(redacted.contains(REDACTED), "no mark left in `{redacted}`");
}
}
}