Skip to content
This repository was archived by the owner on Apr 14, 2025. It is now read-only.

Commit b453929

Browse files
Add postgres tls support
1 parent 9956669 commit b453929

2 files changed

Lines changed: 32 additions & 10 deletions

File tree

src/config.rs

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,7 @@ pub struct Host {
1919
pub port: u16,
2020
pub path: String,
2121
}
22+
2223
#[derive(Deserialize, Clone)]
2324
#[allow(dead_code)]
2425
pub struct DatabaseConfig {
@@ -30,6 +31,8 @@ pub struct DatabaseConfig {
3031
pub pool_max_connections: u32,
3132
pub pool_idle_connections: u32,
3233
pub pool_connection_timeout: u64,
34+
pub ssl_mode: Option<String>,
35+
pub ca_cert: Option<String>,
3336
}
3437
#[derive(Deserialize, Clone)]
3538
pub struct AwsConfig {

src/db/postgres.rs

Lines changed: 29 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -7,29 +7,48 @@ use async_trait::async_trait;
77
use bb8::Pool;
88
use bb8_postgres::PostgresConnectionManager;
99
use chrono::{DateTime, Utc};
10-
use log::debug;
10+
use log::{debug, info};
11+
use native_tls::{Certificate, TlsConnector};
12+
use postgres_native_tls::MakeTlsConnector;
13+
use std::fs;
1114
use std::time::Duration;
12-
use tokio_postgres::NoTls;
1315
use uuid::Uuid;
1416

1517
use super::{DatabaseProvider, DbModerationRow, DbReportRow, Result};
1618

1719
#[derive(Clone)]
1820
pub struct PostgresDatabase {
19-
pool: Pool<PostgresConnectionManager<NoTls>>,
21+
pool: Pool<PostgresConnectionManager<MakeTlsConnector>>,
2022
}
2123

2224
impl PostgresDatabase {
2325
pub async fn new(config: &DatabaseConfig) -> Result<PostgresDatabase> {
26+
let ssl_mode = config
27+
.ssl_mode
28+
.clone()
29+
.unwrap_or_else(|| "prefer".to_string());
30+
31+
info!("Ssl mode for postgres is `{}`", ssl_mode);
32+
2433
let connection_string = format!(
25-
"postgresql://{}:{}@{}:{}",
26-
config.username, config.password, config.host, config.port
34+
"postgresql://{}:{}@{}:{}?sslmode={}",
35+
config.username, config.password, config.host, config.port, ssl_mode
2736
);
28-
let pg_mgr = PostgresConnectionManager::new_from_stringlike(
29-
connection_string,
30-
tokio_postgres::NoTls,
31-
)
32-
.unwrap();
37+
38+
let connector = if let Some(ca_certificate_path) = &config.ca_cert {
39+
info!("Reading ca certificate file from `{}`", ca_certificate_path);
40+
let cert = fs::read(ca_certificate_path)?;
41+
let cert = Certificate::from_pem(&cert)?;
42+
TlsConnector::builder().add_root_certificate(cert).build()?
43+
} else {
44+
info!("Certificate verification will use system specific certificates");
45+
TlsConnector::builder().build()?
46+
};
47+
48+
let connector = MakeTlsConnector::new(connector);
49+
50+
let pg_mgr =
51+
PostgresConnectionManager::new_from_stringlike(connection_string, connector).unwrap();
3352

3453
Ok(PostgresDatabase {
3554
pool: Pool::builder()

0 commit comments

Comments
 (0)