use crate::{
db::MigrationFailureKind,
result::{ClassifyError, DiagnosticKind, ErrorKind},
secret::ExposeSecret,
};
#[cfg(feature = "postgres-admin")]
use super::admin::{PostgresResetError, PostgresResetSettings};
use super::{
POSTGRES_HEALTH_ERROR, PostgresBootstrapError, PostgresBootstrapSettings,
PostgresConnectionSettings, PostgresDiagnosticKind, PostgresHealth, PostgresHealthStatus,
PostgresMigrationRunError, PostgresOperation, PostgresPoolError, PostgresPoolSettings,
PostgresStartupRetrySettings, advisory_lock_key, database_name, diagnose_migration_error,
diagnose_operation_timeout, diagnose_sqlx_error, redact_database_url,
schema_maintenance_advisory_lock_key,
};
#[test]
fn rejects_zero_max_connections() {
let error = PostgresPoolSettings::default()
.with_max_connections(0)
.build()
.expect_err("zero max connections must be rejected");
assert_eq!(error.issues()[0].path(), "postgres.pool.max_connections");
}
#[test]
fn rejects_min_connections_above_max() {
let error = PostgresPoolSettings::default()
.with_max_connections(2)
.with_min_connections(3)
.build()
.expect_err("min connections above max must be rejected");
assert_eq!(error.issues()[0].path(), "postgres.pool.min_connections");
}
#[test]
fn rejects_zero_acquire_timeout() {
let error = PostgresPoolSettings::default()
.with_acquire_timeout(std::time::Duration::ZERO)
.build()
.expect_err("zero acquire timeout must be rejected");
assert_eq!(error.issues()[0].path(), "postgres.pool.acquire_timeout");
}
#[test]
fn rejects_acquire_timeout_outside_the_timer_range() {
let error = PostgresPoolSettings::default()
.with_acquire_timeout(std::time::Duration::MAX)
.build()
.expect_err("unrepresentable deadlines must be rejected before acquiring a connection");
assert_eq!(error.issues()[0].path(), "postgres.pool.acquire_timeout");
assert!(PostgresPoolSettings::default().build().is_ok());
}
#[test]
fn rejects_invalid_pool_maintenance_intervals() {
use std::time::Duration;
for timeout in [Duration::ZERO, Duration::MAX] {
for (settings, field) in [
(
PostgresPoolSettings::default().with_idle_timeout(Some(timeout)),
"idle_timeout",
),
(
PostgresPoolSettings::default().with_max_lifetime(Some(timeout)),
"max_lifetime",
),
] {
let error = settings.build().unwrap_err();
assert_eq!(error.issues()[0].path(), format!("postgres.pool.{field}"));
}
}
PostgresPoolSettings::default()
.with_idle_timeout(None)
.with_max_lifetime(None)
.build()
.unwrap();
}
#[test]
fn rejects_startup_retry_delays_outside_the_timer_range() {
let error = PostgresStartupRetrySettings::default()
.with_max_attempts(2)
.with_initial_delay(std::time::Duration::MAX)
.with_max_delay(std::time::Duration::MAX)
.build()
.unwrap_err();
assert_eq!(error.issues()[0].path(), "postgres.startup_retry.max_delay");
}
#[test]
fn startup_retry_jitter_is_opt_in_and_round_trips_through_settings() {
let defaults: PostgresStartupRetrySettings = serde_json::from_str("{}").unwrap();
assert!(!defaults.build().unwrap().jitter());
let config = PostgresStartupRetrySettings::default()
.with_max_attempts(3)
.with_jitter(true)
.build()
.unwrap();
let wire = serde_json::to_value(PostgresStartupRetrySettings::from(config)).unwrap();
assert_eq!(wire["jitter"], true);
assert!(
serde_json::from_value::<PostgresStartupRetrySettings>(wire)
.unwrap()
.build()
.unwrap()
.jitter()
);
}
#[test]
fn exposes_pool_config_values() {
let config = PostgresPoolSettings::default()
.with_max_connections(20)
.with_min_connections(2)
.with_test_before_acquire(false)
.build()
.expect("pool settings should be valid");
assert_eq!(config.max_connections(), 20);
assert_eq!(config.min_connections(), 2);
assert!(!config.test_before_acquire());
}
#[test]
fn validates_bootstrap_config_before_touching_database() {
let result = PostgresBootstrapSettings::new(" ")
.build()
.expect_err("empty URL should be rejected");
assert_eq!(
result.issues()[0].path(),
"postgres.connection.database_url"
);
let result = PostgresBootstrapSettings::new("not-a-postgres-url")
.build()
.expect_err("invalid URL should be rejected");
assert_eq!(
result.issues()[0].path(),
"postgres.connection.database_url"
);
}
#[tokio::test]
async fn bootstrap_requires_migrator_when_migration_is_enabled() {
let result = super::bootstrap_database(
PostgresBootstrapSettings::new("postgres://postgres:postgres@localhost/app")
.with_migrate_on_startup(true)
.build()
.expect("bootstrap settings should be valid"),
None,
)
.await
.expect_err("missing migrator should be rejected before connecting");
assert!(matches!(result, PostgresBootstrapError::MissingMigrator));
}
#[test]
fn parses_database_name_without_exposing_credentials() {
assert_eq!(
database_name("postgres://app:secret@localhost:5432/app_dev").as_deref(),
Some("app_dev")
);
assert_eq!(database_name("not-a-url"), None);
assert_eq!(
database_name("postgresql://localhost/path?dbname=actual%20database").as_deref(),
Some("actual database")
);
assert_eq!(database_name("postgres://localhost/"), None);
assert_eq!(database_name("postgres://localhost/path?dbname="), None);
assert_eq!(
database_name("postgres://localhost/a%2Fb+c").as_deref(),
Some("a/b+c")
);
assert_eq!(database_name("postgres://localhost/%ff"), None);
assert_eq!(
database_name("postgres://localhost/path?dbname=first&dbname=last+name").as_deref(),
Some("last name")
);
assert_eq!(
database_name("postgres://localhost/app?port=invalid&sslmode=invalid").as_deref(),
Some("app")
);
}
#[test]
fn postgres_settings_still_validate_connection_parameters() {
for parameter in [
"sslmode=invalid",
"port=invalid",
"hostaddr=invalid",
"statement-cache-capacity=invalid",
] {
let url = format!("postgres://localhost/app?{parameter}");
let error = PostgresBootstrapSettings::new(&url).build().unwrap_err();
assert_eq!(error.issues()[0].path(), "postgres.connection.database_url");
#[cfg(feature = "postgres-admin")]
{
let error = PostgresResetSettings::new(&url).build().unwrap_err();
assert_eq!(error.issues()[0].path(), "postgres.reset.database_url");
}
}
let options = super::identity::connect_options(
"postgres://app:secret@localhost/path?dbname=actual&port=5433&application_name=service&options=-c%20search_path%3Dapp&sslmode=disable",
)
.unwrap();
assert_eq!(options.get_database(), Some("actual"));
assert_eq!(options.get_port(), 5433);
assert_eq!(options.get_application_name(), Some("service"));
assert_eq!(options.get_options(), Some("-c search_path=app"));
}
#[test]
fn postgres_settings_reject_ignored_connection_parameters() {
for name in [
"sslmodee",
"statement_timeout",
"connect_timeout",
"%73slmodee",
"options[statement_timeout",
"options[]",
"private-parameter",
] {
let url =
format!("postgres://private-user:private-password@localhost/app?{name}=private-query");
assert_eq!(database_name(&url).as_deref(), Some("app"));
let settings = PostgresConnectionSettings::new(&url);
let error = settings
.validate_at("service.connection")
.expect_err("ignored connection parameters must fail validation");
assert_eq!(error.issues()[0].path(), "service.connection.database_url");
let driver_error = super::identity::connect_options(&url)
.expect_err("unsupported parameters must fail before driver parsing");
assert!(PostgresBootstrapSettings::new(&url).build().is_err());
#[cfg(feature = "postgres-admin")]
assert!(PostgresResetSettings::new(&url).build().is_err());
let output = format!("{error} {error:?} {driver_error} {driver_error:?}");
for sensitive in [
"private-user",
"private-password",
"private-query",
"private-parameter",
] {
assert!(!output.contains(sensitive));
}
}
}
#[test]
fn postgres_connection_parameters_preserve_driver_aliases_and_server_options() {
let url = "postgres://app:secret@localhost/path?ssl-mode=require&ssl-ca=root.pem&ssl-cert=client.pem&ssl-key=client.key&statement-cache-capacity=12&dbname=first&%64bname=actual&options=-c%20search_path%3Dpublic&options%5Bstatement_timeout%5D=1000&options[app.custom_setting]=enabled";
let config = PostgresConnectionSettings::new(url).build().unwrap();
let options = super::connect_options(&config).unwrap();
assert_eq!(database_name(url).as_deref(), options.get_database());
assert_eq!(options.get_database(), Some("actual"));
assert!(matches!(
options.get_ssl_mode(),
sqlx::postgres::PgSslMode::Require
));
assert_eq!(
options.get_options(),
Some("-c search_path=public -c statement_timeout=1000 -c app.custom_setting=enabled")
);
}
#[test]
fn postgres_urls_reject_nul_at_the_security_boundary() {
for url in [
"postgres://localhost/postgres%00application_name%00service",
"postgres://localhost/app?dbname=postgres%00application_name%00service",
"postgres://localhost/app?application_name=service%00database%00postgres",
"postgres://localhost/app?options=-c%20search_path=public%00database%00postgres",
"postgres://user%00application_name%00service@localhost/app",
"postgres://user:private%00password@localhost/app",
"postgres://localhost/app?options[search_path%00database]=public",
"postgres://localhost/app\0suffix",
"postgres://localhost/postgres%0\n0application_name%0\t0service",
] {
assert!(super::identity::connect_options(url).is_err());
assert_eq!(database_name(url), None);
assert_eq!(redact_database_url(url), "<invalid-postgres-url>");
let error = PostgresBootstrapSettings::new(url).build().unwrap_err();
assert_eq!(error.issues()[0].path(), "postgres.connection.database_url");
#[cfg(feature = "postgres-admin")]
{
let error = PostgresResetSettings::new(url).build().unwrap_err();
assert_eq!(error.issues()[0].path(), "postgres.reset.database_url");
}
}
let url = "postgres://localhost/app%2500suffix";
assert_eq!(database_name(url).as_deref(), Some("app%00suffix"));
assert_eq!(
super::identity::connect_options(url)
.unwrap()
.get_database(),
Some("app%00suffix")
);
}
#[cfg(feature = "observability")]
#[tokio::test]
async fn postgres_url_handling_does_not_log_credentials_or_replace_the_callers_subscriber() {
use std::{
io::Write,
sync::{Arc, Mutex},
};
#[derive(Clone)]
struct Output(Arc<Mutex<Vec<u8>>>);
impl Write for Output {
fn write(&mut self, bytes: &[u8]) -> std::io::Result<usize> {
self.0.lock().unwrap().write(bytes)
}
fn flush(&mut self) -> std::io::Result<()> {
Ok(())
}
}
let output = Output(Arc::default());
let writer = output.clone();
let subscriber = tracing_subscriber::fmt()
.without_time()
.with_ansi(false)
.with_max_level(tracing::Level::TRACE)
.with_writer(move || writer.clone())
.finish();
let pool = tracing::subscriber::with_default(subscriber, || {
tracing::info!("before parsing");
let rejected =
"postgres://private-user:private-password@localhost/app?unknown=private-query";
assert!(PostgresConnectionSettings::new(rejected).build().is_err());
let url = "postgres://private-user:private-password@localhost/app?password=private-query";
assert_eq!(database_name(url).as_deref(), Some("app"));
PostgresBootstrapSettings::new(url).build().unwrap();
#[cfg(feature = "postgres-admin")]
PostgresResetSettings::new(url).build().unwrap();
let pool = super::connect_lazy_pool(
&PostgresConnectionSettings::new(url).build().unwrap(),
PostgresPoolSettings::default().build().unwrap(),
)
.unwrap();
let _ = diagnose_sqlx_error(PostgresOperation::Connect, url, &sqlx::Error::PoolTimedOut);
tracing::info!("after parsing");
pool
});
pool.close().await;
let captured = String::from_utf8(output.0.lock().unwrap().clone()).unwrap();
assert!(captured.contains("before parsing"));
assert!(captured.contains("after parsing"));
for value in [
"private-user",
"private-password",
"private-query",
"unknown",
] {
assert!(!captured.contains(value), "unexpected log field: {value}");
}
}
#[test]
fn postgres_settings_reject_urls_for_other_protocols() {
for url in [
"http://localhost/app",
"mysql://localhost/app",
"file:///app",
] {
assert_eq!(database_name(url), None);
let error = PostgresBootstrapSettings::new(url).build().unwrap_err();
assert_eq!(error.issues()[0].path(), "postgres.connection.database_url");
#[cfg(feature = "postgres-admin")]
{
let error = PostgresResetSettings::new(url).build().unwrap_err();
assert_eq!(error.issues()[0].path(), "postgres.reset.database_url");
}
}
}
#[test]
#[cfg(feature = "postgres-admin")]
fn postgres_configuration_debug_redacts_database_urls() {
let database_url =
"postgres://private-user:private-password@localhost/app?password=private-query";
let bootstrap = PostgresBootstrapSettings::new(database_url)
.build()
.expect("bootstrap settings should be valid");
let settings = PostgresBootstrapSettings::new(database_url);
let reset = PostgresResetSettings::new(database_url)
.build()
.expect("reset settings should be valid");
let output = format!("{bootstrap:?} {settings:?} {reset:?}");
assert!(output.contains("[REDACTED]"));
for sensitive in [
database_url,
"private-user",
"private-password",
"private-query",
] {
assert!(!output.contains(sensitive));
}
}
#[derive(Debug, thiserror::Error)]
#[error("{message}")]
pub(super) struct TestDatabaseError {
pub code: &'static str,
pub message: &'static str,
}
impl sqlx::error::DatabaseError for TestDatabaseError {
fn message(&self) -> &str {
self.message
}
fn code(&self) -> Option<std::borrow::Cow<'_, str>> {
Some(self.code.into())
}
fn as_error(&self) -> &(dyn std::error::Error + Send + Sync + 'static) {
self
}
fn as_error_mut(&mut self) -> &mut (dyn std::error::Error + Send + Sync + 'static) {
self
}
fn into_error(self: Box<Self>) -> Box<dyn std::error::Error + Send + Sync + 'static> {
self
}
fn kind(&self) -> sqlx::error::ErrorKind {
sqlx::error::ErrorKind::Other
}
}
fn assert_pool_error_retryability(source: sqlx::Error, retryable: bool) {
let error = PostgresPoolError::Sqlx(source);
let diagnosis = super::diagnose_pool_error(
PostgresOperation::Connect,
"postgres://app:secret@localhost/app",
&error,
);
let descriptor = error.error_descriptor();
assert_eq!(descriptor.retryable(), retryable, "{diagnosis}");
assert_eq!(diagnosis.retryable(), retryable, "{diagnosis}");
assert_eq!(descriptor.kind(), ErrorKind::Dependency);
assert_eq!(descriptor.code().as_str(), "postgres_unavailable");
let bootstrap = PostgresBootstrapError::Connect {
diagnosis,
source: Box::new(error),
};
assert_eq!(bootstrap.error_descriptor().retryable(), retryable);
}
#[test]
fn pool_errors_distinguish_transient_failures_from_permanent_failures() {
for (source, retryable) in [
(
sqlx::Error::Configuration("invalid connection options".into()),
false,
),
(sqlx::Error::Tls("untrusted certificate".into()), false),
(sqlx::Error::PoolClosed, false),
(sqlx::Error::PoolTimedOut, true),
(sqlx::Error::RowNotFound, false),
(sqlx::Error::Protocol("unexpected message".into()), false),
(
sqlx::Error::Io(std::io::ErrorKind::PermissionDenied.into()),
false,
),
(
sqlx::Error::Io(std::io::ErrorKind::ConnectionRefused.into()),
true,
),
(sqlx::Error::Io(std::io::ErrorKind::TimedOut.into()), true),
] {
assert_pool_error_retryability(source, retryable);
}
}
#[test]
fn pool_errors_classify_sqlstate_without_treating_credentials_as_client_faults() {
for (code, retryable) in [
("3D000", false), ("28P01", false), ("28000", false), ("42501", false), ("23505", false), ("53300", true), ("53400", true), ("57P01", true), ("57P02", true), ("57P03", true), ("08006", true), ("XX000", false), ] {
assert_pool_error_retryability(
sqlx::Error::Database(Box::new(TestDatabaseError {
code,
message: "private-driver-error-detail",
})),
retryable,
);
}
}
#[tokio::test]
async fn migration_runner_marks_closed_pool_non_retryable() {
let connection = PostgresConnectionSettings::new("postgres://localhost/app")
.build()
.unwrap();
let pool = super::connect_lazy_pool(&connection, super::PostgresPoolConfig::default()).unwrap();
pool.close().await;
let error = super::run_migrations(&pool, &sqlx::migrate::Migrator::DEFAULT)
.await
.unwrap_err();
assert!(matches!(
error,
PostgresMigrationRunError::Lock(sqlx::Error::PoolClosed)
));
assert!(!error.error_descriptor().retryable());
assert!(
!PostgresBootstrapError::from(error)
.error_descriptor()
.retryable()
);
}
#[test]
fn migration_runner_preserves_source_retryability() {
use sqlx::migrate::MigrateError;
for (error, retryable) in [
(
PostgresMigrationRunError::Lock(sqlx::Error::Configuration(
"private-invalid-options".into(),
)),
false,
),
(
PostgresMigrationRunError::Lock(sqlx::Error::PoolTimedOut),
true,
),
(
PostgresMigrationRunError::Migration(Box::new(MigrateError::Execute(sqlx::Error::Io(
std::io::ErrorKind::ConnectionReset.into(),
)))),
true,
),
(
PostgresMigrationRunError::Migration(Box::new(MigrateError::ExecuteMigration(
sqlx::Error::Database(Box::new(TestDatabaseError {
code: "08006",
message: "private-connection-detail",
})),
1,
))),
true,
),
(
PostgresMigrationRunError::Migration(Box::new(MigrateError::ExecuteMigration(
sqlx::Error::Database(Box::new(TestDatabaseError {
code: "42501",
message: "private-permission-detail",
})),
1,
))),
false,
),
(
PostgresMigrationRunError::Migration(Box::new(MigrateError::VersionMismatch(1))),
false,
),
] {
let descriptor = error.error_descriptor();
assert_eq!(descriptor.retryable(), retryable, "{error:?}");
assert!(!format!("{error} {error:?} {descriptor:?}").contains("private-"));
assert_eq!(
PostgresBootstrapError::from(error)
.error_descriptor()
.retryable(),
retryable,
);
}
}
#[test]
fn postgres_error_formatting_redacts_urls_and_source_details() {
let database_url =
"postgres://private-user:private-password@localhost/app?sslpassword=private-query";
let source_detail = "private-driver-error-detail";
let sqlx_error = sqlx::Error::Database(Box::new(TestDatabaseError {
code: "42501",
message: source_detail,
}));
let diagnosis = diagnose_sqlx_error(PostgresOperation::Connect, database_url, &sqlx_error);
let diagnosis_output = format!("{diagnosis} {diagnosis:?}");
let pool_error = PostgresPoolError::Sqlx(sqlx_error);
let pool_output = format!(
"{pool_error} {pool_error:?} {:?}",
pool_error.error_descriptor()
);
let bootstrap_error = PostgresBootstrapError::Connect {
diagnosis,
source: Box::new(pool_error),
};
let output = format!("{diagnosis_output} {pool_output} {bootstrap_error} {bootstrap_error:?}");
assert!(output.contains("[REDACTED]"));
for sensitive in [
database_url,
"private-user",
"private-password",
"private-query",
source_detail,
] {
assert!(!output.contains(sensitive));
}
}
#[test]
fn postgres_settings_deserialize_credentials_and_redact_debug_output() {
let database_url = "postgres://private-user:private-password@localhost/app";
let settings: PostgresBootstrapSettings = serde_json::from_value(serde_json::json!({
"connection": { "database_url": database_url }
}))
.expect("settings should deserialize");
assert_eq!(
settings.connection.database_url.expose_secret(),
database_url
);
let debug = format!("{settings:?}");
assert!(debug.contains("[REDACTED]"));
assert!(!debug.contains("private-user"));
assert!(!debug.contains("private-password"));
}
#[test]
fn postgres_health_exposes_only_a_stable_redacted_error() {
let health = PostgresHealth {
status: PostgresHealthStatus::Unavailable,
latency: std::time::Duration::from_millis(10),
};
assert_eq!(health.error(), Some("database health check failed"));
let output = format!("{health:?}");
assert!(output.contains("has_error"));
assert!(!output.contains(POSTGRES_HEALTH_ERROR));
}
#[test]
fn postgres_build_validates_the_converted_secret() {
struct ConvertedUrl(&'static str);
impl ExposeSecret<str> for ConvertedUrl {
fn expose_secret(&self) -> &str {
"postgres://localhost/app"
}
}
impl From<ConvertedUrl> for crate::secret::SecretString {
fn from(value: ConvertedUrl) -> Self {
Self::new(value.0)
}
}
let settings = PostgresBootstrapSettings::from_secret(ConvertedUrl("not-a-url"));
settings.validate().unwrap();
let error = settings.build().unwrap_err();
assert_eq!(error.issues()[0].path(), "postgres.connection.database_url");
#[cfg(feature = "postgres-admin")]
for converted_url in ["not-a-url", "postgres://localhost/postgres"] {
let settings = PostgresResetSettings::from_secret(ConvertedUrl(converted_url));
settings.validate().unwrap();
let error = settings.build().unwrap_err();
assert_eq!(error.issues()[0].path(), "postgres.reset.database_url");
}
}
#[test]
fn postgres_settings_convert_to_runtime_config() {
let settings: PostgresBootstrapSettings = PostgresBootstrapSettings {
connection: PostgresConnectionSettings::new("postgres://app:secret@localhost/app"),
pool: PostgresPoolSettings {
max_connections: 20,
..PostgresPoolSettings::default()
},
create_on_startup: true,
ensure_database_timeout: std::time::Duration::from_secs(30),
migrate_on_startup: false,
startup_retry: PostgresStartupRetrySettings::default()
.with_max_attempts(3)
.with_initial_delay(std::time::Duration::from_millis(10))
.with_max_delay(std::time::Duration::from_millis(50)),
migration_lock_key: Some(42),
migration_lock_timeout: std::time::Duration::from_secs(7),
migration_timeout: std::time::Duration::from_secs(90),
};
let config = settings.clone().build().expect("settings should convert");
assert_eq!(
config.database_url().expose_secret(),
"postgres://app:secret@localhost/app"
);
assert_eq!(config.pool_config().max_connections(), 20);
assert!(config.create_on_startup());
assert!(!config.migrate_on_startup());
assert_eq!(config.startup_retry().max_attempts(), 3);
assert_eq!(config.migration_lock_key(), Some(42));
assert_eq!(
config.migration_lock_timeout(),
std::time::Duration::from_secs(7)
);
assert_eq!(
config.migration_timeout(),
std::time::Duration::from_secs(90)
);
let rebuilt = PostgresBootstrapSettings::from(config)
.build()
.expect("runtime config should round-trip through settings");
assert_eq!(rebuilt.migration_lock_key(), Some(42));
assert_eq!(
rebuilt.migration_lock_timeout(),
std::time::Duration::from_secs(7)
);
assert_eq!(
rebuilt.migration_timeout(),
std::time::Duration::from_secs(90)
);
}
#[test]
fn rejects_zero_postgres_advisory_lock_deadlines() {
let bootstrap = PostgresBootstrapSettings::new("postgres://app:secret@localhost/app")
.with_migration_lock_timeout(std::time::Duration::ZERO)
.build()
.expect_err("enabled migration locking must have a deadline");
assert_eq!(
bootstrap.issues()[0].path(),
"postgres.migration_lock_timeout"
);
let migration = PostgresBootstrapSettings::new("postgres://app:secret@localhost/app")
.with_migration_timeout(std::time::Duration::ZERO)
.build()
.expect_err("migration execution must have a deadline");
assert_eq!(migration.issues()[0].path(), "postgres.migration_timeout");
#[cfg(feature = "postgres-admin")]
{
let settings = PostgresResetSettings::new("postgres://app:secret@localhost/app");
let reset = settings
.clone()
.with_reset_lock_timeout(std::time::Duration::ZERO)
.build()
.expect_err("reset locking must have a deadline");
assert_eq!(
reset.issues()[0].path(),
"postgres.reset.reset_lock_timeout"
);
let reset = settings
.clone()
.with_reset_schema_timeout(std::time::Duration::ZERO)
.build()
.expect_err("schema reset must have a deadline");
assert_eq!(
reset.issues()[0].path(),
"postgres.reset.reset_schema_timeout"
);
let reset = settings
.with_post_reset_migration_timeout(std::time::Duration::ZERO)
.build()
.expect_err("post-reset migration must have a deadline");
assert_eq!(
reset.issues()[0].path(),
"postgres.reset.post_reset_migration_timeout"
);
}
}
#[test]
fn rejects_postgres_deadlines_outside_the_runtime_timer_range() {
let bootstrap = PostgresBootstrapSettings::new("postgres://app:secret@localhost/app")
.with_ensure_database_timeout(std::time::Duration::MAX)
.with_migration_lock_timeout(std::time::Duration::MAX)
.with_migration_timeout(std::time::Duration::MAX)
.build()
.expect_err("timer-overflowing migration deadlines must be rejected");
let paths = bootstrap
.issues()
.iter()
.map(|issue| issue.path())
.collect::<Vec<_>>();
assert!(paths.contains(&"postgres.migration_lock_timeout"));
assert!(paths.contains(&"postgres.migration_timeout"));
assert!(paths.contains(&"postgres.ensure_database_timeout"));
#[cfg(feature = "postgres-admin")]
{
let reset = PostgresResetSettings::new("postgres://app:secret@localhost/app")
.with_ensure_database_timeout(std::time::Duration::MAX)
.with_reset_lock_timeout(std::time::Duration::MAX)
.with_reset_schema_timeout(std::time::Duration::MAX)
.with_post_reset_migration_timeout(std::time::Duration::MAX)
.build()
.expect_err("timer-overflowing reset deadlines must be rejected");
let paths = reset
.issues()
.iter()
.map(|issue| issue.path())
.collect::<Vec<_>>();
assert!(paths.contains(&"postgres.reset.reset_lock_timeout"));
assert!(paths.contains(&"postgres.reset.reset_schema_timeout"));
assert!(paths.contains(&"postgres.reset.post_reset_migration_timeout"));
assert!(paths.contains(&"postgres.reset.ensure_database_timeout"));
}
}
#[tokio::test]
async fn database_creation_rejects_invalid_deadlines_before_connecting() {
for timeout in [std::time::Duration::ZERO, std::time::Duration::MAX] {
let error = super::ensure_database_exists("postgres://localhost/app", timeout)
.await
.unwrap_err();
assert!(matches!(error, sqlx::Error::Configuration(_)));
let error = PostgresBootstrapSettings::new("postgres://localhost/app")
.with_ensure_database_timeout(timeout)
.build()
.unwrap_err();
assert_eq!(error.issues()[0].path(), "postgres.ensure_database_timeout");
#[cfg(feature = "postgres-admin")]
{
let error = PostgresResetSettings::new("postgres://localhost/app")
.with_ensure_database_timeout(timeout)
.build()
.unwrap_err();
assert_eq!(
error.issues()[0].path(),
"postgres.reset.ensure_database_timeout"
);
}
}
}
#[test]
fn postgres_bootstrap_timeout_settings_serde_round_trip() {
let settings =
PostgresBootstrapSettings::from_secret("postgres://app:secret@localhost/app".to_owned())
.with_ensure_database_timeout(std::time::Duration::from_secs(7))
.with_additional_migration_advisory_lock(Some(42))
.with_migration_lock_timeout(std::time::Duration::from_secs(11))
.with_migration_timeout(std::time::Duration::from_secs(123));
let json = serde_json::to_string(&settings).expect("settings should serialize");
let decoded: PostgresBootstrapSettings<String> =
serde_json::from_str(&json).expect("settings should deserialize");
assert_eq!(decoded.migration_lock_key, Some(42));
assert_eq!(
decoded.ensure_database_timeout,
std::time::Duration::from_secs(7)
);
assert_eq!(
decoded.migration_lock_timeout,
std::time::Duration::from_secs(11)
);
assert_eq!(
decoded.migration_timeout,
std::time::Duration::from_secs(123)
);
}
#[test]
#[cfg(feature = "postgres-admin")]
fn postgres_reset_timeout_settings_serde_round_trip() {
let settings =
PostgresResetSettings::from_secret("postgres://app:secret@localhost/app".to_owned())
.with_ensure_database_timeout(std::time::Duration::from_secs(7))
.with_reset_lock_timeout(std::time::Duration::from_secs(13))
.with_reset_schema_timeout(std::time::Duration::from_secs(17))
.with_post_reset_migration_timeout(std::time::Duration::from_secs(19));
let json = serde_json::to_string(&settings).expect("settings should serialize");
let decoded: PostgresResetSettings<String> =
serde_json::from_str(&json).expect("settings should deserialize");
assert_eq!(
decoded.ensure_database_timeout,
std::time::Duration::from_secs(7)
);
assert_eq!(
decoded.reset_lock_timeout,
std::time::Duration::from_secs(13)
);
assert_eq!(
decoded.reset_schema_timeout,
std::time::Duration::from_secs(17)
);
assert_eq!(
decoded.post_reset_migration_timeout,
std::time::Duration::from_secs(19)
);
let config = decoded
.build()
.expect("decoded reset settings should build");
assert_eq!(
config.reset_lock_timeout(),
std::time::Duration::from_secs(13)
);
assert_eq!(
config.reset_schema_timeout(),
std::time::Duration::from_secs(17)
);
assert_eq!(
config.post_reset_migration_timeout(),
std::time::Duration::from_secs(19)
);
let rebuilt = PostgresResetSettings::from(config)
.build()
.expect("reset config should round-trip through settings");
assert_eq!(
rebuilt.reset_schema_timeout(),
std::time::Duration::from_secs(17)
);
}
#[test]
fn postgres_settings_adapt_and_validate_with_stable_paths() {
let settings = PostgresBootstrapSettings {
connection: PostgresConnectionSettings::new("postgres://app:secret@localhost/app"),
pool: PostgresPoolSettings {
max_connections: 0,
..PostgresPoolSettings::default()
},
..PostgresBootstrapSettings::new("postgres://app:secret@localhost/app")
};
let validation = settings
.validate_at("database")
.expect_err("invalid settings should report config paths");
assert_eq!(
validation.issues()[0].path(),
"database.pool.max_connections"
);
let error = settings
.clone()
.build()
.expect_err("invalid settings should not build");
assert_eq!(error.issues()[0].path(), "postgres.pool.max_connections");
assert!(settings.validate().is_err());
}
#[test]
fn diagnoses_migration_state_failures_for_operators() {
let missing = sqlx::migrate::MigrateError::VersionMissing(20260428000200);
let diagnosis = diagnose_migration_error("postgres://app:secret@localhost/app", &missing);
assert_eq!(diagnosis.kind(), PostgresDiagnosticKind::MigrationMissing);
assert_eq!(diagnosis.database(), Some("app"));
assert!(diagnosis.message().contains("20260428000200"));
assert!(!diagnosis.retryable());
assert_eq!(
diagnosis.to_diagnostic().kind(),
DiagnosticKind::ResourceMissing
);
let mismatch = sqlx::migrate::MigrateError::VersionMismatch(20260428000200);
assert_eq!(
MigrationFailureKind::from_error(&mismatch),
MigrationFailureKind::VersionMismatch {
version: 20260428000200
}
);
assert_eq!(
diagnose_migration_error("postgres://app:secret@localhost/app", &mismatch).kind(),
PostgresDiagnosticKind::MigrationChecksumMismatch
);
let permission = sqlx::migrate::MigrateError::Execute(sqlx::Error::Io(std::io::Error::new(
std::io::ErrorKind::PermissionDenied,
"socket denied",
)));
assert_eq!(
diagnose_migration_error("postgres://app:secret@localhost/app", &permission).kind(),
PostgresDiagnosticKind::PermissionDenied
);
}
#[test]
fn operation_timeouts_have_stable_redacted_classification() {
let database_url = "postgres://private-user:private-password@localhost/app";
let diagnosis = diagnose_operation_timeout(
PostgresOperation::Migrate,
database_url,
std::time::Duration::from_secs(3),
);
let error = PostgresMigrationRunError::MigrationTimeout {
timeout: std::time::Duration::from_secs(3),
};
let bootstrap_error = PostgresBootstrapError::MigrationTimeout {
diagnosis: diagnosis.clone(),
timeout: std::time::Duration::from_secs(3),
};
let output = format!(
"{diagnosis} {diagnosis:?} {error} {error:?} {bootstrap_error} {bootstrap_error:?}"
);
assert_eq!(diagnosis.kind(), PostgresDiagnosticKind::OperationTimeout);
assert!(diagnosis.retryable());
assert_eq!(error.error_code().as_str(), "postgres_migration_timeout");
assert_eq!(error.error_kind(), ErrorKind::Timeout);
assert_eq!(
bootstrap_error.error_code().as_str(),
"postgres_migration_timeout"
);
assert_eq!(bootstrap_error.error_kind(), ErrorKind::Timeout);
assert!(bootstrap_error.error_descriptor().retryable());
assert!(!output.contains("private-user"));
assert!(!output.contains("private-password"));
#[cfg(feature = "postgres-admin")]
{
let reset_error = PostgresResetError::ResetSchemaTimeout {
diagnosis,
timeout: std::time::Duration::from_secs(3),
};
assert_eq!(
reset_error.error_code().as_str(),
"postgres_reset_schema_timeout"
);
assert_eq!(reset_error.error_kind(), ErrorKind::Timeout);
assert!(reset_error.error_descriptor().retryable());
let reset_output = format!("{reset_error} {reset_error:?}");
assert!(!reset_output.contains("private-user"));
assert!(!reset_output.contains("private-password"));
}
}
#[test]
#[cfg(feature = "postgres-admin")]
fn reset_config_rejects_system_databases() {
let system = PostgresResetSettings::new("postgres://app:secret@localhost/postgres")
.build()
.expect_err("system database should be rejected");
assert_eq!(system.issues()[0].path(), "postgres.reset.database_url");
}
#[test]
fn redacts_database_urls_without_losing_routing_information() {
assert_eq!(
redact_database_url("postgres://app:secret@localhost:5432/app"),
"postgres://app:****@localhost:5432/app"
);
assert_eq!(
redact_database_url(
"postgres://app:secret@localhost/app?sslmode=require&sslpassword=private-query"
),
"postgres://app:****@localhost/app?sslmode=****&sslpassword=****"
);
assert_eq!(
redact_database_url("postgres://localhost/app?password=private-query#private-fragment"),
"postgres://localhost/app?password=****#****"
);
assert_eq!(redact_database_url("not-a-url"), "<invalid-postgres-url>");
}
#[test]
fn database_url_redaction_uses_parsed_components() {
for (input, expected) in [
(
"postgresql://app:p%2Frivate%3F%23%40@[::1]:5433/my%20db?password=first&password=second#private",
"postgresql://app:****@[::1]:5433/my%20db?password=****&password=****#****",
),
(
"postgres://app@localhost/app",
"postgres://****@localhost/app",
),
(
"postgres:///app?host=%2Fvar%2Frun%2Fpostgresql",
"postgres:///app?host=****",
),
(
"postgres://localhost/app?options=-c%20private%3Dvalue&flag",
"postgres://localhost/app?options=****&flag=****",
),
] {
assert_eq!(redact_database_url(input), expected);
}
}
#[test]
fn database_url_redaction_never_echoes_unparseable_or_unsupported_urls() {
for input in [
"not-a-url",
"postgres://app:private/secret@localhost/app",
"postgres://app:private?secret@localhost/app",
"postgres://app:private#secret@localhost/app",
"postgres://app:private@[invalid-host/app",
"mysql://app:private@localhost/app",
"postgres:production?password=private",
] {
assert_eq!(redact_database_url(input), "<invalid-postgres-url>");
}
}
#[test]
fn advisory_lock_keys_are_stable_and_namespaced() {
let left = advisory_lock_key("app", "migrations");
let same = advisory_lock_key(" app ", " migrations ");
let other = advisory_lock_key("app", "workers");
assert_eq!(left, same);
assert_ne!(left, other);
let maintenance = schema_maintenance_advisory_lock_key("app");
assert_eq!(
super::runtime::schema_maintenance_lock_keys("app", Some(maintenance)),
vec![maintenance]
);
assert_eq!(
super::runtime::schema_maintenance_lock_keys("app", Some(other)),
vec![maintenance, other]
);
}
#[test]
fn pool_options_preserve_disabled_and_explicit_recycling_timeouts() {
use std::time::Duration;
for (idle, lifetime) in [
(None, None),
(Some(Duration::from_secs(7)), None),
(None, Some(Duration::from_secs(19))),
(Some(Duration::from_secs(7)), Some(Duration::from_secs(19))),
] {
let config = PostgresPoolSettings::default()
.with_idle_timeout(idle)
.with_max_lifetime(lifetime)
.build()
.unwrap();
let options = super::pool_options(config);
assert_eq!(options.get_idle_timeout(), idle);
assert_eq!(options.get_max_lifetime(), lifetime);
}
}