@@ -7,29 +7,48 @@ use async_trait::async_trait;
77use bb8:: Pool ;
88use bb8_postgres:: PostgresConnectionManager ;
99use 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;
1114use std:: time:: Duration ;
12- use tokio_postgres:: NoTls ;
1315use uuid:: Uuid ;
1416
1517use super :: { DatabaseProvider , DbModerationRow , DbReportRow , Result } ;
1618
1719#[ derive( Clone ) ]
1820pub struct PostgresDatabase {
19- pool : Pool < PostgresConnectionManager < NoTls > > ,
21+ pool : Pool < PostgresConnectionManager < MakeTlsConnector > > ,
2022}
2123
2224impl 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