]> Untitled Git - lemmy.git/blob - crates/db_schema/src/utils.rs
Add support for sslmode=require for diesel-async DB connections (#3189)
[lemmy.git] / crates / db_schema / src / utils.rs
1 use crate::{
2   diesel::Connection,
3   diesel_migrations::MigrationHarness,
4   newtypes::DbUrl,
5   CommentSortType,
6   SortType,
7 };
8 use activitypub_federation::{fetch::object_id::ObjectId, traits::Object};
9 use chrono::NaiveDateTime;
10 use deadpool::Runtime;
11 use diesel::{
12   backend::Backend,
13   deserialize::FromSql,
14   pg::Pg,
15   result::{ConnectionError, ConnectionResult, Error as DieselError, Error::QueryBuilderError},
16   serialize::{Output, ToSql},
17   sql_types::Text,
18   PgConnection,
19 };
20 use diesel_async::{
21   pg::AsyncPgConnection,
22   pooled_connection::{
23     deadpool::{Object as PooledConnection, Pool},
24     AsyncDieselConnectionManager,
25   },
26 };
27 use diesel_migrations::EmbeddedMigrations;
28 use futures_util::{future::BoxFuture, FutureExt};
29 use lemmy_utils::{error::LemmyError, settings::structs::Settings};
30 use once_cell::sync::Lazy;
31 use regex::Regex;
32 use rustls::{
33   client::{ServerCertVerified, ServerCertVerifier},
34   ServerName,
35 };
36 use std::{
37   env,
38   env::VarError,
39   sync::Arc,
40   time::{Duration, SystemTime},
41 };
42 use tracing::{error, info};
43 use url::Url;
44
45 const FETCH_LIMIT_DEFAULT: i64 = 10;
46 pub const FETCH_LIMIT_MAX: i64 = 50;
47 const POOL_TIMEOUT: Option<Duration> = Some(Duration::from_secs(5));
48
49 pub type DbPool = Pool<AsyncPgConnection>;
50
51 pub async fn get_conn(pool: &DbPool) -> Result<PooledConnection<AsyncPgConnection>, DieselError> {
52   pool.get().await.map_err(|e| QueryBuilderError(e.into()))
53 }
54
55 pub fn get_database_url_from_env() -> Result<String, VarError> {
56   env::var("LEMMY_DATABASE_URL")
57 }
58
59 pub fn fuzzy_search(q: &str) -> String {
60   let replaced = q.replace('%', "\\%").replace('_', "\\_").replace(' ', "%");
61   format!("%{replaced}%")
62 }
63
64 pub fn limit_and_offset(
65   page: Option<i64>,
66   limit: Option<i64>,
67 ) -> Result<(i64, i64), diesel::result::Error> {
68   let page = match page {
69     Some(page) => {
70       if page < 1 {
71         return Err(QueryBuilderError("Page is < 1".into()));
72       } else {
73         page
74       }
75     }
76     None => 1,
77   };
78   let limit = match limit {
79     Some(limit) => {
80       if !(1..=FETCH_LIMIT_MAX).contains(&limit) {
81         return Err(QueryBuilderError(
82           format!("Fetch limit is > {FETCH_LIMIT_MAX}").into(),
83         ));
84       } else {
85         limit
86       }
87     }
88     None => FETCH_LIMIT_DEFAULT,
89   };
90   let offset = limit * (page - 1);
91   Ok((limit, offset))
92 }
93
94 pub fn limit_and_offset_unlimited(page: Option<i64>, limit: Option<i64>) -> (i64, i64) {
95   let limit = limit.unwrap_or(FETCH_LIMIT_DEFAULT);
96   let offset = limit * (page.unwrap_or(1) - 1);
97   (limit, offset)
98 }
99
100 pub fn is_email_regex(test: &str) -> bool {
101   EMAIL_REGEX.is_match(test)
102 }
103
104 pub fn diesel_option_overwrite(opt: &Option<String>) -> Option<Option<String>> {
105   match opt {
106     // An empty string is an erase
107     Some(unwrapped) => {
108       if !unwrapped.eq("") {
109         Some(Some(unwrapped.clone()))
110       } else {
111         Some(None)
112       }
113     }
114     None => None,
115   }
116 }
117
118 pub fn diesel_option_overwrite_to_url(
119   opt: &Option<String>,
120 ) -> Result<Option<Option<DbUrl>>, LemmyError> {
121   match opt.as_ref().map(std::string::String::as_str) {
122     // An empty string is an erase
123     Some("") => Ok(Some(None)),
124     Some(str_url) => match Url::parse(str_url) {
125       Ok(url) => Ok(Some(Some(url.into()))),
126       Err(e) => Err(LemmyError::from_error_message(e, "invalid_url")),
127     },
128     None => Ok(None),
129   }
130 }
131
132 pub fn diesel_option_overwrite_to_url_create(
133   opt: &Option<String>,
134 ) -> Result<Option<DbUrl>, LemmyError> {
135   match opt.as_ref().map(std::string::String::as_str) {
136     // An empty string is nothing
137     Some("") => Ok(None),
138     Some(str_url) => match Url::parse(str_url) {
139       Ok(url) => Ok(Some(url.into())),
140       Err(e) => Err(LemmyError::from_error_message(e, "invalid_url")),
141     },
142     None => Ok(None),
143   }
144 }
145
146 async fn build_db_pool_settings_opt(settings: Option<&Settings>) -> Result<DbPool, LemmyError> {
147   let db_url = get_database_url(settings);
148   let pool_size = settings.map(|s| s.database.pool_size).unwrap_or(5);
149   // We only support TLS with sslmode=require currently
150   let tls_enabled = db_url.contains("sslmode=require");
151   let manager = if tls_enabled {
152     // diesel-async does not support any TLS connections out of the box, so we need to manually
153     // provide a setup function which handles creating the connection
154     AsyncDieselConnectionManager::<AsyncPgConnection>::new_with_setup(&db_url, establish_connection)
155   } else {
156     AsyncDieselConnectionManager::<AsyncPgConnection>::new(&db_url)
157   };
158   let pool = Pool::builder(manager)
159     .max_size(pool_size)
160     .wait_timeout(POOL_TIMEOUT)
161     .create_timeout(POOL_TIMEOUT)
162     .recycle_timeout(POOL_TIMEOUT)
163     .runtime(Runtime::Tokio1)
164     .build()?;
165
166   // If there's no settings, that means its a unit test, and migrations need to be run
167   if settings.is_none() {
168     run_migrations(&db_url);
169   }
170
171   Ok(pool)
172 }
173
174 fn establish_connection(config: &str) -> BoxFuture<ConnectionResult<AsyncPgConnection>> {
175   let fut = async {
176     let rustls_config = rustls::ClientConfig::builder()
177       .with_safe_defaults()
178       .with_custom_certificate_verifier(Arc::new(NoCertVerifier {}))
179       .with_no_client_auth();
180
181     let tls = tokio_postgres_rustls::MakeRustlsConnect::new(rustls_config);
182     let (client, conn) = tokio_postgres::connect(config, tls)
183       .await
184       .map_err(|e| ConnectionError::BadConnection(e.to_string()))?;
185     tokio::spawn(async move {
186       if let Err(e) = conn.await {
187         error!("Database connection failed: {e}");
188       }
189     });
190     AsyncPgConnection::try_from(client).await
191   };
192   fut.boxed()
193 }
194
195 struct NoCertVerifier {}
196
197 impl ServerCertVerifier for NoCertVerifier {
198   fn verify_server_cert(
199     &self,
200     _end_entity: &rustls::Certificate,
201     _intermediates: &[rustls::Certificate],
202     _server_name: &ServerName,
203     _scts: &mut dyn Iterator<Item = &[u8]>,
204     _ocsp_response: &[u8],
205     _now: SystemTime,
206   ) -> Result<ServerCertVerified, rustls::Error> {
207     // Will verify all (even invalid) certs without any checks (sslmode=require)
208     Ok(ServerCertVerified::assertion())
209   }
210 }
211
212 pub const MIGRATIONS: EmbeddedMigrations = embed_migrations!();
213
214 pub fn run_migrations(db_url: &str) {
215   // Needs to be a sync connection
216   let mut conn =
217     PgConnection::establish(db_url).unwrap_or_else(|e| panic!("Error connecting to {db_url}: {e}"));
218   info!("Running Database migrations (This may take a long time)...");
219   let _ = &mut conn
220     .run_pending_migrations(MIGRATIONS)
221     .unwrap_or_else(|e| panic!("Couldn't run DB Migrations: {e}"));
222   info!("Database migrations complete.");
223 }
224
225 pub async fn build_db_pool(settings: &Settings) -> Result<DbPool, LemmyError> {
226   build_db_pool_settings_opt(Some(settings)).await
227 }
228
229 pub async fn build_db_pool_for_tests() -> DbPool {
230   build_db_pool_settings_opt(None)
231     .await
232     .expect("db pool missing")
233 }
234
235 pub fn get_database_url(settings: Option<&Settings>) -> String {
236   // The env var should override anything in the settings config
237   match get_database_url_from_env() {
238     Ok(url) => url,
239     Err(e) => match settings {
240       Some(settings) => settings.get_database_url(),
241       None => panic!("Failed to read database URL from env var LEMMY_DATABASE_URL: {e}"),
242     },
243   }
244 }
245
246 pub fn naive_now() -> NaiveDateTime {
247   chrono::prelude::Utc::now().naive_utc()
248 }
249
250 pub fn post_to_comment_sort_type(sort: SortType) -> CommentSortType {
251   match sort {
252     SortType::Active | SortType::Hot => CommentSortType::Hot,
253     SortType::New | SortType::NewComments | SortType::MostComments => CommentSortType::New,
254     SortType::Old => CommentSortType::Old,
255     SortType::TopHour
256     | SortType::TopSixHour
257     | SortType::TopTwelveHour
258     | SortType::TopDay
259     | SortType::TopAll
260     | SortType::TopWeek
261     | SortType::TopYear
262     | SortType::TopMonth => CommentSortType::Top,
263   }
264 }
265
266 static EMAIL_REGEX: Lazy<Regex> = Lazy::new(|| {
267   Regex::new(r"^[a-zA-Z0-9.!#$%&’*+/=?^_`{|}~-]+@[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$")
268     .expect("compile email regex")
269 });
270
271 pub mod functions {
272   use diesel::sql_types::{BigInt, Text, Timestamp};
273
274   sql_function! {
275     fn hot_rank(score: BigInt, time: Timestamp) -> Integer;
276   }
277
278   sql_function!(fn lower(x: Text) -> Text);
279 }
280
281 impl ToSql<Text, Pg> for DbUrl {
282   fn to_sql(&self, out: &mut Output<Pg>) -> diesel::serialize::Result {
283     <std::string::String as ToSql<Text, Pg>>::to_sql(&self.0.to_string(), &mut out.reborrow())
284   }
285 }
286
287 impl<DB: Backend> FromSql<Text, DB> for DbUrl
288 where
289   String: FromSql<Text, DB>,
290 {
291   fn from_sql(value: DB::RawValue<'_>) -> diesel::deserialize::Result<Self> {
292     let str = String::from_sql(value)?;
293     Ok(DbUrl(Box::new(Url::parse(&str)?)))
294   }
295 }
296
297 impl<Kind> From<ObjectId<Kind>> for DbUrl
298 where
299   Kind: Object + Send + 'static,
300   for<'de2> <Kind as Object>::Kind: serde::Deserialize<'de2>,
301 {
302   fn from(id: ObjectId<Kind>) -> Self {
303     DbUrl(Box::new(id.into()))
304   }
305 }
306
307 #[cfg(test)]
308 mod tests {
309   use super::{fuzzy_search, *};
310   use crate::utils::is_email_regex;
311
312   #[test]
313   fn test_fuzzy_search() {
314     let test = "This %is% _a_ fuzzy search";
315     assert_eq!(
316       fuzzy_search(test),
317       "%This%\\%is\\%%\\_a\\_%fuzzy%search%".to_string()
318     );
319   }
320
321   #[test]
322   fn test_email() {
323     assert!(is_email_regex("gush@gmail.com"));
324     assert!(!is_email_regex("nada_neutho"));
325   }
326
327   #[test]
328   fn test_diesel_option_overwrite() {
329     assert_eq!(diesel_option_overwrite(&None), None);
330     assert_eq!(diesel_option_overwrite(&Some(String::new())), Some(None));
331     assert_eq!(
332       diesel_option_overwrite(&Some("test".to_string())),
333       Some(Some("test".to_string()))
334     );
335   }
336
337   #[test]
338   fn test_diesel_option_overwrite_to_url() {
339     assert!(matches!(diesel_option_overwrite_to_url(&None), Ok(None)));
340     assert!(matches!(
341       diesel_option_overwrite_to_url(&Some(String::new())),
342       Ok(Some(None))
343     ));
344     assert!(matches!(
345       diesel_option_overwrite_to_url(&Some("invalid_url".to_string())),
346       Err(_)
347     ));
348     let example_url = "https://example.com";
349     assert!(matches!(
350       diesel_option_overwrite_to_url(&Some(example_url.to_string())),
351       Ok(Some(Some(url))) if url == Url::parse(example_url).unwrap().into()
352     ));
353   }
354 }