feat: protect secrets

This commit is contained in:
Sandro Eiler 2024-02-04 14:03:52 +01:00
parent 93140e7d22
commit e3d8c967f5
5 changed files with 43 additions and 18 deletions

View file

@ -1,3 +1,5 @@
use secrecy::{ExposeSecret, Secret};
#[derive(serde::Deserialize)]
/// The application's settings
///
@ -18,7 +20,7 @@ pub struct Settings {
/// * `name`: the DB name
pub struct DatabaseSettings {
pub username: String,
pub password: String,
pub password: Secret<String>,
pub port: u16,
pub host: String,
pub name: String,
@ -38,17 +40,24 @@ pub fn get_configuration() -> Result<Settings, config::ConfigError> {
}
impl DatabaseSettings {
pub fn connection_string(&self) -> String {
format!(
pub fn connection_string(&self) -> Secret<String> {
Secret::new(format!(
"postgres://{}:{}@{}:{}/{}",
self.username, self.password, self.host, self.port, self.name
)
self.username,
self.password.expose_secret(),
self.host,
self.port,
self.name
))
}
pub fn connection_string_without_db(&self) -> String {
format!(
pub fn connection_string_without_db(&self) -> Secret<String> {
Secret::new(format!(
"postgres://{}:{}@{}:{}",
self.username, self.password, self.host, self.port
)
self.username,
self.password.expose_secret(),
self.host,
self.port
))
}
}

View file

@ -1,6 +1,7 @@
use learn_axum::configuration::get_configuration;
use learn_axum::startup;
use learn_axum::telemetry::{get_subscriber, init_subscriber};
use secrecy::ExposeSecret;
use sqlx::PgPool;
use tokio::net::TcpListener;
@ -14,8 +15,9 @@ async fn main() {
let configuration = get_configuration().expect("Failed to read configuration.");
let addr = format!("127.0.0.1:{}", configuration.application_port);
let listener = TcpListener::bind(addr).await.unwrap(); //.expect("Unable to bind to port");
let connection_pool = PgPool::connect(&configuration.database.connection_string())
.await
.expect("Failed to connect to Postgres.");
let connection_pool =
PgPool::connect(configuration.database.connection_string().expose_secret())
.await
.expect("Failed to connect to Postgres.");
startup::run(listener, connection_pool).await.unwrap();
}