diff --git a/Cargo.lock b/Cargo.lock index ebbaa40..c2be988 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -618,6 +618,7 @@ dependencies = [ "reqwest", "secrecy", "serde", + "serde-aux", "sqlx", "tokio", "tracing", @@ -1987,6 +1988,17 @@ dependencies = [ "serde_derive", ] +[[package]] +name = "serde-aux" +version = "4.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0d2e8bfba469d06512e11e3311d4d051a4a387a5b42d010404fecf3200321c95" +dependencies = [ + "chrono", + "serde", + "serde_json", +] + [[package]] name = "serde_derive" version = "1.0.197" diff --git a/Cargo.toml b/Cargo.toml index 4eb9b7c..dd99487 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -30,6 +30,7 @@ once_cell = "1.19.0" secrecy = { version = "0.8.0", features = ["serde"] } tracing-actix-web = "0.7.10" h2 = "0.3.26" +serde-aux = "4.5.0" [dependencies.sqlx] version = "0.7" diff --git a/configuration/local.yaml b/configuration/local.yaml index c464c2f..8fd67fa 100644 --- a/configuration/local.yaml +++ b/configuration/local.yaml @@ -1,2 +1,4 @@ application: host: 127.0.0.1 +database: + require_ssl: false diff --git a/configuration/production.yaml b/configuration/production.yaml index b936a88..cd4608a 100644 --- a/configuration/production.yaml +++ b/configuration/production.yaml @@ -1,2 +1,4 @@ application: host: 0.0.0.0 +database: + require_ssl: true diff --git a/src/configuration.rs b/src/configuration.rs index 907ead9..bcc4471 100644 --- a/src/configuration.rs +++ b/src/configuration.rs @@ -1,4 +1,7 @@ use secrecy::{ExposeSecret, Secret}; +use serde_aux::field_attributes::deserialize_number_from_string; +use sqlx::postgres::{PgConnectOptions, PgSslMode}; +use sqlx::ConnectOptions; #[derive(serde::Deserialize)] pub struct Settings { @@ -8,6 +11,7 @@ pub struct Settings { #[derive(serde::Deserialize)] pub struct ApplicationSettings { + #[serde(deserialize_with = "deserialize_number_from_string")] pub port: u16, pub host: String, } @@ -16,9 +20,11 @@ pub struct ApplicationSettings { pub struct DatabaseSettings { pub username: String, pub password: Secret, + #[serde(deserialize_with = "deserialize_number_from_string")] pub port: u16, pub host: String, pub database_name: String, + pub require_ssl: bool, } pub fn get_configuration() -> Result { @@ -39,6 +45,15 @@ pub fn get_configuration() -> Result { .add_source(config::File::from( configuration_directory.join(environment_filename), )) + // take settings from environment variables + // with a prefix of APP and __ as separator + // + // E.g `APP_APPLICATION_PORT=5001` would set Settings.application.port + .add_source( + config::Environment::with_prefix("APP") + .prefix_separator("_") + .separator("__"), + ) .build()?; settings.try_deserialize::() @@ -73,24 +88,26 @@ Use either `local` or `production`.", } impl DatabaseSettings { - pub fn connection_string(&self) -> Secret { - Secret::new(format!( - "postgres://{}:{}@{}:{}/{}", - self.username, - self.password.expose_secret(), - self.host, - self.port, - self.database_name - )) + // for normal usage + pub fn with_db(&self) -> PgConnectOptions { + let mut options = self.without_db().database(&self.database_name); + options = options.log_statements(tracing_log::log::LevelFilter::Trace); + options } - pub fn connection_string_without_db(&self) -> Secret { - Secret::new(format!( - "postgres://{}:{}@{}:{}", - self.username, - self.password.expose_secret(), - self.host, - self.port - )) + // for testings, we will set the database name with arbitrary values + pub fn without_db(&self) -> PgConnectOptions { + let ssl_mode = if self.require_ssl { + PgSslMode::Require + } else { + PgSslMode::Prefer + }; + + PgConnectOptions::new() + .host(&self.host) + .username(&self.username) + .password(self.password.expose_secret()) + .port(self.port) + .ssl_mode(ssl_mode) } } diff --git a/src/main.rs b/src/main.rs index f033756..6bd23f4 100644 --- a/src/main.rs +++ b/src/main.rs @@ -2,8 +2,7 @@ use std::net::TcpListener; use email_newsletter_api::telemetry::{get_subscriber, init_subscriber}; use email_newsletter_api::{configuration::get_configuration, startup}; -use secrecy::ExposeSecret; -use sqlx::PgPool; +use sqlx::postgres::PgPoolOptions; #[tokio::main] async fn main() -> Result<(), std::io::Error> { @@ -16,8 +15,7 @@ async fn main() -> Result<(), std::io::Error> { ); init_subscriber(subscriber); - let db_conn = PgPool::connect_lazy(configuration.database.connection_string().expose_secret()) - .expect("Failed to connect to PostgreSQL"); + let db_conn = PgPoolOptions::new().connect_lazy_with(configuration.database.with_db()); let listener = TcpListener::bind(format!( "{}:{}", diff --git a/tests/test_utils.rs b/tests/test_utils.rs index 4b1a157..138032d 100644 --- a/tests/test_utils.rs +++ b/tests/test_utils.rs @@ -3,7 +3,6 @@ use email_newsletter_api::{ telemetry::{get_subscriber, init_subscriber}, }; use once_cell::sync::Lazy; -use secrecy::ExposeSecret; use sqlx::{Connection, Executor, PgConnection, PgPool}; use std::net::TcpListener; use uuid::Uuid; @@ -58,17 +57,16 @@ pub async fn spawn_app() -> TestApp { } pub async fn configure_test_database(db_config: &DatabaseSettings) -> PgPool { - let mut connection = - PgConnection::connect(db_config.connection_string_without_db().expose_secret()) - .await - .expect("Failed to connect to Postgres"); + let mut connection = PgConnection::connect_with(&db_config.without_db()) + .await + .expect("Failed to connect to Postgres"); connection .execute(format!(r#"CREATE DATABASE "{}";"#, db_config.database_name).as_str()) .await .expect("Failed to create database"); - let conn_pool = PgPool::connect(db_config.connection_string().expose_secret()) + let conn_pool = PgPool::connect_with(db_config.with_db()) .await .expect("Failed to connect to PostgreSQL pool");