Support for TLS encryption

This commit is contained in:
Alphonse Paix
2025-09-05 18:13:35 +02:00
parent 767fc571b6
commit a7d22e6634
8 changed files with 97 additions and 26 deletions

View File

@@ -9,10 +9,10 @@ use axum::{
routing::{get, post},
};
use axum_messages::MessagesManagerLayer;
use axum_server::tls_rustls::RustlsConfig;
use secrecy::ExposeSecret;
use sqlx::{PgPool, postgres::PgPoolOptions};
use std::sync::Arc;
use tokio::net::TcpListener;
use std::{net::TcpListener, sync::Arc};
use tower_http::trace::TraceLayer;
use tower_sessions::SessionManagerLayer;
use tower_sessions_redis_store::{
@@ -21,11 +21,6 @@ use tower_sessions_redis_store::{
};
use uuid::Uuid;
pub struct Application {
listener: TcpListener,
router: Router,
}
#[derive(Clone)]
pub struct AppState {
pub connection_pool: PgPool,
@@ -33,13 +28,19 @@ pub struct AppState {
pub base_url: String,
}
pub struct Application {
listener: TcpListener,
router: Router,
tls_config: Option<RustlsConfig>,
}
impl Application {
pub async fn build(configuration: Settings) -> Result<Self, std::io::Error> {
pub async fn build(configuration: Settings) -> Result<Self, anyhow::Error> {
let address = format!(
"{}:{}",
configuration.application.host, configuration.application.port
);
let listener = TcpListener::bind(address).await?;
// let listener = TcpListener::bind(address).await?;
let connection_pool =
PgPoolOptions::new().connect_lazy_with(configuration.database.with_db());
let email_client = EmailClient::build(configuration.email_client).unwrap();
@@ -61,17 +62,46 @@ impl Application {
configuration.application.base_url,
redis_store,
);
Ok(Self { listener, router })
let tls_config = if configuration.application.require_tls {
Some(
RustlsConfig::from_pem_file(
"/home/alphonse/.certs/fullchain.pem",
"/home/alphonse/.certs/privkey.pem",
)
.await
.unwrap(),
)
} else {
None
};
let listener = TcpListener::bind(address).unwrap();
Ok(Self {
listener,
router,
tls_config,
})
}
pub async fn run_until_stopped(self) -> Result<(), std::io::Error> {
tracing::debug!("listening on {}", self.listener.local_addr().unwrap());
axum::serve(self.listener, self.router).await
tracing::debug!("listening on {}", self.local_addr());
if let Some(tls_config) = self.tls_config {
axum_server::from_tcp_rustls(self.listener, tls_config)
.serve(self.router.into_make_service())
.await
} else {
axum_server::from_tcp(self.listener)
.serve(self.router.into_make_service())
.await
}
}
pub fn local_addr(&self) -> String {
self.listener.local_addr().unwrap().to_string()
}
pub fn port(&self) -> u16 {
self.listener.local_addr().unwrap().port()
}
}
pub fn app(