use crate::config::{PgConfig, SslMode};
use crate::error::PgResult;
#[derive(Clone)]
pub(crate) enum Connector {
NoTls,
#[cfg(feature = "tls")]
Rustls(postgres_rustls::MakeTlsConnector),
}
pub(crate) fn select_connector(config: &PgConfig) -> PgResult<Connector> {
#[cfg(feature = "tls")]
{
match config.ssl_mode {
SslMode::Disable => Ok(Connector::NoTls),
_ => Ok(Connector::Rustls(
crate::tls::make_tls_connector_with_root_cert(config.ssl_root_cert.as_deref())?,
)),
}
}
#[cfg(not(feature = "tls"))]
{
match config.ssl_mode {
SslMode::Disable => Ok(Connector::NoTls),
SslMode::Prefer => Ok(Connector::NoTls),
other => Err(crate::error::PgError::config(format!(
"ssl_mode {:?} requires TLS support; rebuild prax-postgres \
with the `tls` feature (enabled by default)",
other
))),
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::config::PgConfig;
#[test]
fn disable_selects_no_tls() {
let config = PgConfig::from_url("postgres://u@h/db?sslmode=disable").unwrap();
assert!(matches!(select_connector(&config), Ok(Connector::NoTls)));
}
#[cfg(feature = "tls")]
#[test]
fn require_selects_rustls_with_tls_feature() {
let config = PgConfig::from_url("postgres://u@h/db?sslmode=require").unwrap();
assert!(matches!(
select_connector(&config),
Ok(Connector::Rustls(_))
));
}
#[cfg(not(feature = "tls"))]
#[test]
fn require_is_a_config_error_without_tls_feature() {
let config = PgConfig::from_url("postgres://u@h/db?sslmode=require").unwrap();
assert!(matches!(
select_connector(&config),
Err(crate::error::PgError::Config(_))
));
}
}