]> Untitled Git - lemmy.git/blobdiff - crates/apub/src/lib.rs
Make functions work with both connection and pool (#3420)
[lemmy.git] / crates / apub / src / lib.rs
index 43e26961ccc55580f9132006173cb87e0afc85b9..8d818602262eb031971edd65649f1ac1f9dc7804 100644 (file)
@@ -9,11 +9,13 @@ use lemmy_db_schema::{
     local_site::LocalSite,
   },
   traits::Crud,
-  utils::DbPool,
+  utils::{ActualDbPool, DbPool},
 };
-use lemmy_utils::{error::LemmyError, settings::structs::Settings};
+use lemmy_utils::error::{LemmyError, LemmyErrorType, LemmyResult};
+use moka::future::Cache;
 use once_cell::sync::Lazy;
 use serde::Serialize;
+use std::{sync::Arc, time::Duration};
 use url::Url;
 
 pub mod activities;
@@ -27,18 +29,23 @@ pub mod objects;
 pub mod protocol;
 
 pub const FEDERATION_HTTP_FETCH_LIMIT: u32 = 50;
+/// All incoming and outgoing federation actions read the blocklist/allowlist and slur filters
+/// multiple times. This causes a huge number of database reads if we hit the db directly. So we
+/// cache these values for a short time, which will already make a huge difference and ensures that
+/// changes take effect quickly.
+const BLOCKLIST_CACHE_DURATION: Duration = Duration::from_secs(60);
 
 static CONTEXT: Lazy<Vec<serde_json::Value>> = Lazy::new(|| {
   serde_json::from_str(include_str!("../assets/lemmy/context.json")).expect("parse context")
 });
 
 #[derive(Clone)]
-pub struct VerifyUrlData(pub DbPool);
+pub struct VerifyUrlData(pub ActualDbPool);
 
 #[async_trait]
 impl UrlVerifier for VerifyUrlData {
   async fn verify(&self, url: &Url) -> Result<(), &'static str> {
-    let local_site_data = fetch_local_site_data(&self.0)
+    let local_site_data = local_site_data_cached(&mut (&self.0).into())
       .await
       .expect("read local site data");
     check_apub_id_valid(url, &local_site_data)?;
@@ -53,9 +60,6 @@ impl UrlVerifier for VerifyUrlData {
 /// - the correct scheme (either http or https)
 /// - URL being in the allowlist (if it is active)
 /// - URL not being in the blocklist (if it is active)
-///
-/// `use_strict_allowlist` should be true only when parsing a remote community, or when parsing a
-/// post/comment in a local community.
 #[tracing::instrument(skip(local_site_data))]
 fn check_apub_id_valid(apub_id: &Url, local_site_data: &LocalSiteData) -> Result<(), &'static str> {
   let domain = apub_id.domain().expect("apud id has domain").to_string();
@@ -69,16 +73,22 @@ fn check_apub_id_valid(apub_id: &Url, local_site_data: &LocalSiteData) -> Result
     return Err("Federation disabled");
   }
 
-  if let Some(blocked) = local_site_data.blocked_instances.as_ref() {
-    if blocked.iter().any(|i| domain.eq(&i.domain)) {
-      return Err("Domain is blocked");
-    }
+  if local_site_data
+    .blocked_instances
+    .iter()
+    .any(|i| domain.eq(&i.domain))
+  {
+    return Err("Domain is blocked");
   }
 
-  if let Some(allowed) = local_site_data.allowed_instances.as_ref() {
-    if !allowed.iter().any(|i| domain.eq(&i.domain)) {
-      return Err("Domain is not in allowlist");
-    }
+  // Only check this if there are instances in the allowlist
+  if !local_site_data.allowed_instances.is_empty()
+    && !local_site_data
+      .allowed_instances
+      .iter()
+      .any(|i| domain.eq(&i.domain))
+  {
+    return Err("Domain is not in allowlist");
   }
 
   Ok(())
@@ -87,65 +97,82 @@ fn check_apub_id_valid(apub_id: &Url, local_site_data: &LocalSiteData) -> Result
 #[derive(Clone)]
 pub(crate) struct LocalSiteData {
   local_site: Option<LocalSite>,
-  allowed_instances: Option<Vec<Instance>>,
-  blocked_instances: Option<Vec<Instance>>,
+  allowed_instances: Vec<Instance>,
+  blocked_instances: Vec<Instance>,
 }
 
-pub(crate) async fn fetch_local_site_data(
-  pool: &DbPool,
-) -> Result<LocalSiteData, diesel::result::Error> {
-  // LocalSite may be missing
-  let local_site = LocalSite::read(pool).await.ok();
-  let allowed = Instance::allowlist(pool).await?;
-  let blocked = Instance::blocklist(pool).await?;
-
-  // These can return empty vectors, so convert them to options
-  let allowed_instances = (!allowed.is_empty()).then_some(allowed);
-  let blocked_instances = (!blocked.is_empty()).then_some(blocked);
-
-  Ok(LocalSiteData {
-    local_site,
-    allowed_instances,
-    blocked_instances,
-  })
+pub(crate) async fn local_site_data_cached(
+  pool: &mut DbPool<'_>,
+) -> LemmyResult<Arc<LocalSiteData>> {
+  static CACHE: Lazy<Cache<(), Arc<LocalSiteData>>> = Lazy::new(|| {
+    Cache::builder()
+      .max_capacity(1)
+      .time_to_live(BLOCKLIST_CACHE_DURATION)
+      .build()
+  });
+  Ok(
+    CACHE
+      .try_get_with((), async {
+        let (local_site, allowed_instances, blocked_instances) =
+          lemmy_db_schema::try_join_with_pool!(pool => (
+            // LocalSite may be missing
+            |pool| async {
+              Ok(LocalSite::read(pool).await.ok())
+            },
+            Instance::allowlist,
+            Instance::blocklist
+          ))?;
+
+        Ok::<_, diesel::result::Error>(Arc::new(LocalSiteData {
+          local_site,
+          allowed_instances,
+          blocked_instances,
+        }))
+      })
+      .await?,
+  )
 }
 
-#[tracing::instrument(skip(settings, local_site_data))]
-pub(crate) fn check_apub_id_valid_with_strictness(
+pub(crate) async fn check_apub_id_valid_with_strictness(
   apub_id: &Url,
   is_strict: bool,
-  local_site_data: &LocalSiteData,
-  settings: &Settings,
+  context: &LemmyContext,
 ) -> Result<(), LemmyError> {
   let domain = apub_id.domain().expect("apud id has domain").to_string();
-  let local_instance = settings
+  let local_instance = context
+    .settings()
     .get_hostname_without_port()
     .expect("local hostname is valid");
   if domain == local_instance {
     return Ok(());
   }
-  check_apub_id_valid(apub_id, local_site_data).map_err(LemmyError::from_message)?;
-
-  if let Some(allowed) = local_site_data.allowed_instances.as_ref() {
-    // Only check allowlist if this is a community
-    if is_strict {
-      // need to allow this explicitly because apub receive might contain objects from our local
-      // instance.
-      let mut allowed_and_local = allowed
-        .iter()
-        .map(|i| i.domain.clone())
-        .collect::<Vec<String>>();
-      let local_instance = settings
-        .get_hostname_without_port()
-        .expect("local hostname is valid");
-      allowed_and_local.push(local_instance);
-
-      let domain = apub_id.domain().expect("apud id has domain").to_string();
-      if !allowed_and_local.contains(&domain) {
-        return Err(LemmyError::from_message(
-          "Federation forbidden by strict allowlist",
-        ));
-      }
+
+  let local_site_data = local_site_data_cached(&mut context.pool()).await?;
+  check_apub_id_valid(apub_id, &local_site_data).map_err(|err| match err {
+    "Federation disabled" => LemmyErrorType::FederationDisabled,
+    "Domain is blocked" => LemmyErrorType::DomainBlocked,
+    "Domain is not in allowlist" => LemmyErrorType::DomainNotInAllowList,
+    _ => panic!("Could not handle apub error!"),
+  })?;
+
+  // Only check allowlist if this is a community, and there are instances in the allowlist
+  if is_strict && !local_site_data.allowed_instances.is_empty() {
+    // need to allow this explicitly because apub receive might contain objects from our local
+    // instance.
+    let mut allowed_and_local = local_site_data
+      .allowed_instances
+      .iter()
+      .map(|i| i.domain.clone())
+      .collect::<Vec<String>>();
+    let local_instance = context
+      .settings()
+      .get_hostname_without_port()
+      .expect("local hostname is valid");
+    allowed_and_local.push(local_instance);
+
+    let domain = apub_id.domain().expect("apud id has domain").to_string();
+    if !allowed_and_local.contains(&domain) {
+      return Err(LemmyErrorType::FederationDisabledByStrictAllowList)?;
     }
   }
   Ok(())
@@ -174,13 +201,13 @@ where
     sensitive: Some(sensitive),
     updated: None,
   };
-  Activity::create(data.pool(), &form).await?;
+  Activity::create(&mut data.pool(), &form).await?;
   Ok(())
 }
 
 #[async_trait::async_trait]
 pub trait SendActivity: Sync {
-  type Response: Sync + Send;
+  type Response: Sync + Send + Clone;
 
   async fn send_activity(
     _request: &Self,