feat: add ssh for database access

This commit is contained in:
Sandro Eiler 2024-02-07 21:59:28 +01:00
parent 1d5b9699b9
commit 13162f6470
5 changed files with 29 additions and 26 deletions

View file

@ -1,2 +1,4 @@
application: application:
host: 127.0.0.1 host: 127.0.0.1
database:
require_ssl: false

View file

@ -1,2 +1,4 @@
application: application:
host: 0.0.0.0 host: 0.0.0.0
database:
require_ssl: true

View file

@ -1,5 +1,8 @@
use secrecy::{ExposeSecret, Secret}; use secrecy::{ExposeSecret, Secret};
use serde_aux::field_attributes::deserialize_number_from_string; use serde_aux::field_attributes::deserialize_number_from_string;
use sqlx::postgres::PgConnectOptions;
use sqlx::postgres::PgSslMode;
use sqlx::ConnectOptions;
#[derive(serde::Deserialize)] #[derive(serde::Deserialize)]
/// The setting collection. /// The setting collection.
@ -102,24 +105,24 @@ pub fn get_configuration() -> Result<Settings, config::ConfigError> {
} }
impl DatabaseSettings { impl DatabaseSettings {
pub fn connection_string(&self) -> Secret<String> { pub fn without_db(&self) -> PgConnectOptions {
Secret::new(format!( let ssl_mode = if self.require_ssl {
"postgres://{}:{}@{}:{}/{}", PgSslMode::Require
self.username, } else {
self.password.expose_secret(), // Try an encrypted connection, fallback to unencrypted if it fails
self.host, PgSslMode::Prefer
self.port, };
self.name PgConnectOptions::new()
)) .host(&self.host)
.username(&self.username)
.password(self.password.expose_secret())
.port(self.port)
.ssl_mode(ssl_mode)
} }
pub fn connection_string_without_db(&self) -> Secret<String> { pub fn with_db(&self) -> PgConnectOptions {
Secret::new(format!( let mut options = self.without_db().database(&self.name);
"postgres://{}:{}@{}:{}", options = options.log_statements(tracing::log::LevelFilter::Trace);
self.username, options
self.password.expose_secret(),
self.host,
self.port
))
} }
} }

View file

@ -1,7 +1,6 @@
use learn_axum::configuration::get_configuration; use learn_axum::configuration::get_configuration;
use learn_axum::startup; use learn_axum::startup;
use learn_axum::telemetry::{get_subscriber, init_subscriber}; use learn_axum::telemetry::{get_subscriber, init_subscriber};
use secrecy::ExposeSecret;
use sqlx::postgres::PgPoolOptions; use sqlx::postgres::PgPoolOptions;
use tokio::net::TcpListener; use tokio::net::TcpListener;
@ -20,7 +19,6 @@ async fn main() {
let listener = TcpListener::bind(addr).await.unwrap(); //.expect("Unable to bind to port"); let listener = TcpListener::bind(addr).await.unwrap(); //.expect("Unable to bind to port");
let connection_pool = PgPoolOptions::new() let connection_pool = PgPoolOptions::new()
.acquire_timeout(std::time::Duration::from_secs(2)) .acquire_timeout(std::time::Duration::from_secs(2))
.connect_lazy(configuration.database.connection_string().expose_secret()) .connect_lazy_with(configuration.database.with_db());
.expect("Failed to connect to Postgres.");
startup::run(listener, connection_pool).await.unwrap(); startup::run(listener, connection_pool).await.unwrap();
} }

View file

@ -1,7 +1,6 @@
use learn_axum::configuration::{get_configuration, DatabaseSettings}; use learn_axum::configuration::{get_configuration, DatabaseSettings};
use learn_axum::telemetry::{get_subscriber, init_subscriber}; use learn_axum::telemetry::{get_subscriber, init_subscriber};
use once_cell::sync::Lazy; use once_cell::sync::Lazy;
use secrecy::ExposeSecret;
use sqlx::{Connection, Executor, PgConnection, PgPool}; use sqlx::{Connection, Executor, PgConnection, PgPool};
use tokio::net::TcpListener; use tokio::net::TcpListener;
use uuid::Uuid; use uuid::Uuid;
@ -129,8 +128,7 @@ async fn spawn_app() -> TestApp {
pub async fn configure_database(config: &DatabaseSettings) -> PgPool { pub async fn configure_database(config: &DatabaseSettings) -> PgPool {
// Create database // Create database
let mut connection = let mut connection = PgConnection::connect_with(&config.without_db())
PgConnection::connect(&config.connection_string_without_db().expose_secret())
.await .await
.expect("Failed to connect to Postgres"); .expect("Failed to connect to Postgres");
connection connection
@ -139,7 +137,7 @@ pub async fn configure_database(config: &DatabaseSettings) -> PgPool {
.expect("Failed to create database."); .expect("Failed to create database.");
// Migrate database // Migrate database
let connection_pool = PgPool::connect(&config.connection_string().expose_secret()) let connection_pool = PgPool::connect_with(config.with_db())
.await .await
.expect("Failed to connect to Postgres."); .expect("Failed to connect to Postgres.");
sqlx::migrate!("./migrations") sqlx::migrate!("./migrations")