use std::error::Error as _;
use std::fmt;
use std::net::IpAddr;
use std::sync::Arc;
use std::time::Duration;
use rustls::ClientConfig;
use tokio_postgres::config::{ChannelBinding, SslMode, TargetSessionAttrs};
use tokio_postgres::{Client, SimpleQueryMessage};
use tokio_postgres_rustls::MakeRustlsConnect;
use zeroize::Zeroizing;
use super::secrets::Secrets;
use crate::config::{PostgresSettings, StorageError};
pub(crate) const APPLICATION_NAME: &str = "vcon-server";
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct Target {
pub(crate) host: String,
pub(crate) addr: Option<IpAddr>,
pub(crate) port: u16,
}
impl fmt::Display for Target {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
if self.host.contains(':') {
write!(f, "[{}]:{}", self.host, self.port)
} else {
write!(f, "{}:{}", self.host, self.port)
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct Server {
pub(crate) target: String,
pub(crate) version: String,
pub(crate) user: String,
pub(crate) pid: i32,
}
impl fmt::Display for Server {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(
f,
"PostgreSQL {} at {} as {} over TLS",
self.version, self.target, self.user
)
}
}
pub(crate) struct Connected {
pub(crate) client: Client,
pub(crate) server: Server,
}
impl fmt::Debug for Connected {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("Connected")
.field("server", &self.server)
.finish_non_exhaustive()
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct ConnectError(pub(crate) Vec<(String, String)>);
impl fmt::Display for ConnectError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let tries: Vec<String> = self
.0
.iter()
.map(|(target, why)| format!("{target}: {why}"))
.collect();
write!(f, "no server could be used: {}", tries.join("; "))
}
}
impl std::error::Error for ConnectError {}
pub(crate) struct Connector {
targets: Vec<Target>,
dbname: String,
user: String,
password: Option<Zeroizing<String>>,
tls: MakeRustlsConnect,
connect_timeout: Duration,
options: String,
}
impl fmt::Debug for Connector {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("Connector")
.field("targets", &self.targets)
.field("dbname", &self.dbname)
.field("user", &self.user)
.finish_non_exhaustive()
}
}
pub(crate) fn session_options(statement_timeout: Duration, lock_timeout: Duration) -> String {
format!(
"-c statement_timeout={} -c lock_timeout={}",
statement_timeout.as_millis(),
lock_timeout.as_millis()
)
}
pub(crate) fn tls_config(secrets: &Secrets) -> Result<ClientConfig, StorageError> {
let provider = Arc::new(rustls::crypto::aws_lc_rs::default_provider());
let builder = ClientConfig::builder_with_provider(provider)
.with_safe_default_protocol_versions()
.map_err(|e| StorageError(format!("catalog.postgres: TLS cannot be set up: {e}")))?
.with_root_certificates(secrets.roots.clone());
match &secrets.client {
None => Ok(builder.with_no_client_auth()),
Some((chain, key)) => builder
.with_client_auth_cert(chain.clone(), key.clone_key())
.map_err(|e| {
StorageError(format!(
"catalog.postgres.client_key_file: the key cannot be used with \
catalog.postgres.client_cert_file: {e}"
))
}),
}
}
impl Connector {
pub(crate) fn new(
settings: &PostgresSettings,
secrets: Secrets,
) -> Result<Connector, StorageError> {
let targets = settings
.hosts
.iter()
.map(|host| Target {
host: host.clone(),
addr: None,
port: settings.port,
})
.collect();
Connector::to(targets, settings, secrets)
}
pub(crate) fn to(
targets: Vec<Target>,
settings: &PostgresSettings,
secrets: Secrets,
) -> Result<Connector, StorageError> {
let tls = MakeRustlsConnect::new(tls_config(&secrets)?);
Ok(Connector {
targets,
dbname: settings.dbname.clone(),
user: settings.user.clone(),
password: secrets.password,
tls,
connect_timeout: settings.connect_timeout,
options: session_options(settings.statement_timeout, settings.lock_timeout),
})
}
pub(crate) async fn connect(&self) -> Result<Connected, ConnectError> {
let mut refused = Vec::new();
for target in &self.targets {
let tried = tokio::time::timeout(self.connect_timeout, self.connect_to(target)).await;
match tried {
Ok(Ok(connected)) => return Ok(connected),
Ok(Err(why)) => refused.push((target.to_string(), why)),
Err(_) => refused.push((
target.to_string(),
format!(
"no answer within catalog.postgres.connect_timeout ({} s)",
self.connect_timeout.as_secs()
),
)),
}
}
Err(ConnectError(refused))
}
async fn connect_to(&self, target: &Target) -> Result<Connected, String> {
let mut config = tokio_postgres::Config::new();
config
.host(&target.host)
.port(target.port)
.dbname(&self.dbname)
.user(&self.user)
.application_name(APPLICATION_NAME)
.options(&self.options)
.connect_timeout(self.connect_timeout)
.ssl_mode(SslMode::Require)
.target_session_attrs(TargetSessionAttrs::Any);
if let Some(addr) = target.addr {
config.hostaddr(addr);
}
match &self.password {
Some(password) => {
config
.password(password.as_bytes())
.channel_binding(ChannelBinding::Require);
}
None => {
config.channel_binding(ChannelBinding::Disable);
}
}
let (client, connection) = config
.connect(self.tls.clone())
.await
.map_err(|e| why(&e))?;
drop(config);
tokio::spawn(async move {
let _closed = connection.await;
});
let server = check(&client, target).await?;
Ok(Connected { client, server })
}
}
fn why(e: &tokio_postgres::Error) -> String {
let text = with_causes(e);
if let Some(db) = e.as_db_error() {
return format!(
"the server refused: {} (SQLSTATE {})",
db.message(),
db.code().code()
);
}
if text.contains("server did not use channel binding") {
return format!(
"{text}: with a password, the only login accepted is SCRAM-SHA-256 with channel \
binding; give the role a scram-sha-256 line under hostssl in pg_hba.conf (md5, \
password and trust are refused)"
);
}
if text.contains("password missing") {
return format!(
"{text}: the server asked for a password, and catalog.postgres has no \
password_file"
);
}
if text.contains("server does not support TLS") {
return format!("{text}: turn ssl on in the server's postgresql.conf");
}
if let Some(why) = certificate_problem(e) {
return format!("{text}: {why}");
}
text
}
fn certificate_problem(e: &tokio_postgres::Error) -> Option<&'static str> {
use rustls::{AlertDescription, CertificateError};
let mut source = e.source();
while let Some(cause) = source {
let tls = cause
.downcast_ref::<std::io::Error>()
.and_then(|io| io.get_ref())
.and_then(|inner| inner.downcast_ref::<rustls::Error>());
if let Some(rustls::Error::InvalidCertificate(why)) = tls {
return Some(match why {
CertificateError::UnknownIssuer | CertificateError::BadSignature => {
"the server's certificate is not signed by an authority in \
catalog.postgres.ca_file (or the system's, without it)"
}
CertificateError::NotValidForName
| CertificateError::NotValidForNameContext { .. } => {
"the server's certificate does not hold the host name it was reached by"
}
CertificateError::Expired | CertificateError::ExpiredContext { .. } => {
"the server's certificate has expired"
}
_ => "the server's certificate is refused",
});
}
if let Some(rustls::Error::AlertReceived(
AlertDescription::UnknownCA
| AlertDescription::BadCertificate
| AlertDescription::CertificateRequired
| AlertDescription::CertificateExpired
| AlertDescription::CertificateRevoked
| AlertDescription::CertificateUnknown
| AlertDescription::UnsupportedCertificate,
)) = tls
{
return Some(
"the server refused the client certificate (catalog.postgres.client_cert_file): \
the server's ssl_ca_file must hold the authority that signed it",
);
}
source = cause.source();
}
None
}
pub(crate) fn with_causes(e: &dyn std::error::Error) -> String {
let mut text = e.to_string();
let mut source = e.source();
while let Some(cause) = source {
text.push_str(": ");
text.push_str(&cause.to_string());
source = cause.source();
}
text
}
async fn check(client: &Client, target: &Target) -> Result<Server, String> {
const CHECK: &str = "SELECT pg_is_in_recovery(), current_setting('transaction_read_only'), \
r.rolsuper, r.rolbypassrls, current_setting('server_version'), \
pg_backend_pid(), current_user FROM pg_roles r \
WHERE r.rolname = current_user";
let messages = client
.simple_query(CHECK)
.await
.map_err(|e| format!("the server cannot be checked: {}", with_causes(&e)))?;
let row = messages
.iter()
.find_map(|m| match m {
SimpleQueryMessage::Row(row) => Some(row),
_ => None,
})
.ok_or_else(|| {
"the server cannot be checked: pg_roles has no row for this role".to_owned()
})?;
let text = |i: usize| row.get(i).unwrap_or_default();
let user = text(6).to_owned();
if text(0) == "t" {
return Err(
"the server is a standby (pg_is_in_recovery() is true); name the primary".to_owned(),
);
}
if text(1) == "on" {
return Err(
"the server takes only read-only transactions (transaction_read_only is on); name \
a primary that takes writes"
.to_owned(),
);
}
if text(2) == "t" {
return Err(format!(
"the role {user:?} is a superuser, which passes row-level security; log in as a \
role that is not"
));
}
if text(3) == "t" {
return Err(format!(
"the role {user:?} has BYPASSRLS, which passes row-level security; log in as a role \
without it"
));
}
Ok(Server {
target: target.to_string(),
version: text(4).to_owned(),
user,
pid: text(5).parse().map_err(|_| {
"the server cannot be checked: pg_backend_pid() is not a number".to_owned()
})?,
})
}