diff --git a/Cargo.lock b/Cargo.lock index d10a7ec..565ede9 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2041,6 +2041,17 @@ dependencies = [ "serde_derive", ] +[[package]] +name = "serde-aux" +version = "4.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "184eba62ebddb71658697c8b08822edee89970bf318c5362189f0de27f85b498" +dependencies = [ + "chrono", + "serde", + "serde_json", +] + [[package]] name = "serde_derive" version = "1.0.188" @@ -3080,6 +3091,7 @@ dependencies = [ "reqwest", "secrecy", "serde", + "serde-aux", "sqlx", "tokio", "tracing", diff --git a/Cargo.toml b/Cargo.toml index b3a74dc..12bf30b 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -18,6 +18,7 @@ chrono = "0.4.26" config = "0.13.3" reqwest = "0.11.18" serde = {version = "1", features = ["std", "serde_derive"]} +serde-aux = "4" sqlx = { version = "0.7.1", features = ["runtime-tokio", "tls-rustls", "postgres", "chrono", "uuid", "migrate"] } tokio = { version = "1", features = ["macros", "rt-multi-thread"] } uuid = {version ="1.4.1", features = ["v4", "fast-rng"]} diff --git a/configuration/local.yaml b/configuration/local.yaml index d4147f8..62017b3 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/spec.yaml b/spec.yaml index 1b58521..ad14ed0 100644 --- a/spec.yaml +++ b/spec.yaml @@ -1,7 +1,3 @@ -# I am not even sure why I have this, digitalocean just fails with a cryptic -# error message on some file it could not find, does not tell me what it is, and -# half the lines of the logs are completely broken. I guess I won't lose any -# money. name: zero2prod region: fra1 services: @@ -19,6 +15,22 @@ services: instance_size_slug: basic-xxs routes: - path: / + envs: + - key: APP_DATABASE__USERNAME + scope: RUN_TIME + value: ${newsletter.USERNAME} + - key: APP_DATABASE__PASSWORD + scope: RUN_TIME + value: ${newsletter.PASSWORD} + - key: APP_DATABASE__HOST + scope: RUN_TIME + value: ${newsletter.HOSTNAME} + - key: APP_DATABASE__PORT + scope: RUN_TIME + value: ${newsletter.PORT} + - key: APP_DATABASE__DATABASE_NAME + scope: RUN_TIME + value: ${newsletter.DATABASE} databases: - engine: PG name: newsletter diff --git a/src/configuration.rs b/src/configuration.rs index 211f48d..16adc70 100644 --- a/src/configuration.rs +++ b/src/configuration.rs @@ -1,6 +1,10 @@ -use std::convert::TryFrom; - use secrecy::{ExposeSecret, Secret}; +use serde_aux::field_attributes::deserialize_number_from_string; +use sqlx::{ + postgres::{PgConnectOptions, PgSslMode}, + ConnectOptions, +}; +use std::convert::TryFrom; #[derive(serde::Deserialize)] pub struct Settings { @@ -18,30 +22,32 @@ 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, } 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 - )) + pub fn with_db(&self) -> PgConnectOptions { + self.without_db() + .database(&self.database_name) + .log_statements(tracing_log::log::LevelFilter::Trace) } - pub fn connection_string_without_db(&self) -> Secret { - Secret::new(format!( - "postgres://{}:{}@{}:{}", - self.username, - self.password.expose_secret(), - self.host, - self.port - )) + pub fn without_db(&self) -> PgConnectOptions { + let ssl_mode = if self.require_ssl { + PgSslMode::Require + } else { + //Try encrypted connected but fall back if unavailable. + PgSslMode::Prefer + }; + PgConnectOptions::new() + .host(&self.host) + .username(&self.username) + .password(self.password.expose_secret()) + .port(self.port) + .ssl_mode(ssl_mode) } } @@ -93,6 +99,13 @@ pub fn get_configuration() -> Result { .add_source(config::File::from( configuration_directory.join(env.as_str()), )) + .add_source( + // This will match things like: APP_APPLICATION__PORT=5001 which is + // Settings.application.port + config::Environment::with_prefix("APP") + .prefix_separator("_") + .separator("__"), + ) .build()?; settings.try_deserialize::() diff --git a/src/main.rs b/src/main.rs index 9af1a63..9d248df 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1,4 +1,3 @@ -use secrecy::ExposeSecret; use sqlx::postgres::PgPoolOptions; use zero2prod::{configuration::get_configuration, startup::run, telemetry::*}; @@ -14,8 +13,7 @@ async fn main() -> Result<(), std::io::Error> { ); let db_pool = PgPoolOptions::new() .idle_timeout(std::time::Duration::from_secs(2)) - .connect_lazy(configuration.database.connection_string().expose_secret()) - .expect("Failed to create database connection"); + .connect_lazy_with(configuration.database.with_db()); run( std::net::TcpListener::bind(address).expect("Failed to bind to port"), db_pool, diff --git a/tests/api/check_health.rs b/tests/api/check_health.rs index 4cd6df9..61b227e 100644 --- a/tests/api/check_health.rs +++ b/tests/api/check_health.rs @@ -1,7 +1,5 @@ -use std::sync::OnceLock; - -use secrecy::ExposeSecret; use sqlx::{Connection, Executor}; +use std::sync::OnceLock; use zero2prod::{ configuration::{get_configuration, DatabaseSettings}, startup::run, @@ -56,17 +54,16 @@ pub async fn spawn_app() -> TestApp { } async fn configure_database(config: &DatabaseSettings) -> sqlx::PgPool { - let mut connection = - sqlx::PgConnection::connect(&config.connection_string_without_db().expose_secret()) - .await - .expect("Failed to connect to postgres instance"); + let mut connection = sqlx::PgConnection::connect_with(&config.without_db()) + .await + .expect("Failed to connect to postgres instance"); connection .execute(format!(r#"CREATE DATABASE "{}""#, config.database_name,).as_str()) .await .expect("Failed to create new database"); - let db_pool = sqlx::PgPool::connect(&config.connection_string().expose_secret()) + let db_pool = sqlx::PgPool::connect_with(config.with_db()) .await .expect("Failed to connect to database"); sqlx::migrate!("./migrations")