]> Untitled Git - lemmy.git/blob - crates/apub/src/lib.rs
Add SendActivity trait so that api crates compile in parallel with lemmy_apub
[lemmy.git] / crates / apub / src / lib.rs
1 use crate::fetcher::post_or_comment::PostOrComment;
2 use activitypub_federation::{
3   core::signatures::PublicKey,
4   traits::{Actor, ApubObject},
5   InstanceSettings,
6   LocalInstance,
7   UrlVerifier,
8 };
9 use async_trait::async_trait;
10 use lemmy_api_common::context::LemmyContext;
11 use lemmy_db_schema::{
12   source::{activity::Activity, instance::Instance, local_site::LocalSite},
13   utils::DbPool,
14 };
15 use lemmy_utils::{error::LemmyError, settings::structs::Settings};
16 use once_cell::sync::Lazy;
17 use tokio::sync::OnceCell;
18 use url::Url;
19
20 pub mod activities;
21 pub(crate) mod activity_lists;
22 pub mod api;
23 pub(crate) mod collections;
24 pub mod fetcher;
25 pub mod http;
26 pub(crate) mod mentions;
27 pub mod objects;
28 pub mod protocol;
29
30 const FEDERATION_HTTP_FETCH_LIMIT: i32 = 25;
31
32 static CONTEXT: Lazy<Vec<serde_json::Value>> = Lazy::new(|| {
33   serde_json::from_str(include_str!("../assets/lemmy/context.json")).expect("parse context")
34 });
35
36 // TODO: store this in context? but its only used in this crate, no need to expose it elsewhere
37 // TODO this singleton needs to be redone to account for live data.
38 async fn local_instance(context: &LemmyContext) -> &'static LocalInstance {
39   static LOCAL_INSTANCE: OnceCell<LocalInstance> = OnceCell::const_new();
40   LOCAL_INSTANCE
41     .get_or_init(|| async {
42       // Local site may be missing
43       let local_site = &LocalSite::read(context.pool()).await;
44       let worker_count = local_site
45         .as_ref()
46         .map(|l| l.federation_worker_count)
47         .unwrap_or(64) as u64;
48       let federation_debug = local_site
49         .as_ref()
50         .map(|l| l.federation_debug)
51         .unwrap_or(true);
52
53       let settings = InstanceSettings::builder()
54         .http_fetch_retry_limit(FEDERATION_HTTP_FETCH_LIMIT)
55         .worker_count(worker_count)
56         .debug(federation_debug)
57         .http_signature_compat(true)
58         .url_verifier(Box::new(VerifyUrlData(context.clone())))
59         .build()
60         .expect("configure federation");
61       LocalInstance::new(
62         context.settings().hostname.clone(),
63         context.client().clone(),
64         settings,
65       )
66     })
67     .await
68 }
69
70 #[derive(Clone)]
71 struct VerifyUrlData(LemmyContext);
72
73 #[async_trait]
74 impl UrlVerifier for VerifyUrlData {
75   async fn verify(&self, url: &Url) -> Result<(), &'static str> {
76     let local_site_data = fetch_local_site_data(self.0.pool())
77       .await
78       .expect("read local site data");
79     check_apub_id_valid(url, &local_site_data, self.0.settings())
80   }
81 }
82
83 /// Checks if the ID is allowed for sending or receiving.
84 ///
85 /// In particular, it checks for:
86 /// - federation being enabled (if its disabled, only local URLs are allowed)
87 /// - the correct scheme (either http or https)
88 /// - URL being in the allowlist (if it is active)
89 /// - URL not being in the blocklist (if it is active)
90 ///
91 /// `use_strict_allowlist` should be true only when parsing a remote community, or when parsing a
92 /// post/comment in a local community.
93 #[tracing::instrument(skip(settings, local_site_data))]
94 fn check_apub_id_valid(
95   apub_id: &Url,
96   local_site_data: &LocalSiteData,
97   settings: &Settings,
98 ) -> Result<(), &'static str> {
99   let domain = apub_id.domain().expect("apud id has domain").to_string();
100   let local_instance = settings
101     .get_hostname_without_port()
102     .expect("local hostname is valid");
103   if domain == local_instance {
104     return Ok(());
105   }
106
107   if !local_site_data
108     .local_site
109     .as_ref()
110     .map(|l| l.federation_enabled)
111     .unwrap_or(true)
112   {
113     return Err("Federation disabled");
114   }
115
116   if apub_id.scheme() != settings.get_protocol_string() {
117     return Err("Invalid protocol scheme");
118   }
119
120   if let Some(blocked) = local_site_data.blocked_instances.as_ref() {
121     if blocked.contains(&domain) {
122       return Err("Domain is blocked");
123     }
124   }
125
126   if let Some(allowed) = local_site_data.allowed_instances.as_ref() {
127     if !allowed.contains(&domain) {
128       return Err("Domain is not in allowlist");
129     }
130   }
131
132   Ok(())
133 }
134
135 #[derive(Clone)]
136 pub(crate) struct LocalSiteData {
137   local_site: Option<LocalSite>,
138   allowed_instances: Option<Vec<String>>,
139   blocked_instances: Option<Vec<String>>,
140 }
141
142 pub(crate) async fn fetch_local_site_data(
143   pool: &DbPool,
144 ) -> Result<LocalSiteData, diesel::result::Error> {
145   // LocalSite may be missing
146   let local_site = LocalSite::read(pool).await.ok();
147   let allowed = Instance::allowlist(pool).await?;
148   let blocked = Instance::blocklist(pool).await?;
149
150   // These can return empty vectors, so convert them to options
151   let allowed_instances = (!allowed.is_empty()).then_some(allowed);
152   let blocked_instances = (!blocked.is_empty()).then_some(blocked);
153
154   Ok(LocalSiteData {
155     local_site,
156     allowed_instances,
157     blocked_instances,
158   })
159 }
160
161 #[tracing::instrument(skip(settings, local_site_data))]
162 pub(crate) fn check_apub_id_valid_with_strictness(
163   apub_id: &Url,
164   is_strict: bool,
165   local_site_data: &LocalSiteData,
166   settings: &Settings,
167 ) -> Result<(), LemmyError> {
168   check_apub_id_valid(apub_id, local_site_data, settings).map_err(LemmyError::from_message)?;
169   let domain = apub_id.domain().expect("apud id has domain").to_string();
170   let local_instance = settings
171     .get_hostname_without_port()
172     .expect("local hostname is valid");
173   if domain == local_instance {
174     return Ok(());
175   }
176
177   if let Some(allowed) = local_site_data.allowed_instances.as_ref() {
178     // Only check allowlist if this is a community
179     if is_strict {
180       // need to allow this explicitly because apub receive might contain objects from our local
181       // instance.
182       let mut allowed_and_local = allowed.clone();
183       allowed_and_local.push(local_instance);
184
185       if !allowed_and_local.contains(&domain) {
186         return Err(LemmyError::from_message(
187           "Federation forbidden by strict allowlist",
188         ));
189       }
190     }
191   }
192   Ok(())
193 }
194
195 /// Store a sent or received activity in the database, for logging purposes. These records are not
196 /// persistent.
197 #[tracing::instrument(skip(pool))]
198 async fn insert_activity(
199   ap_id: &Url,
200   activity: serde_json::Value,
201   local: bool,
202   sensitive: bool,
203   pool: &DbPool,
204 ) -> Result<bool, LemmyError> {
205   let ap_id = ap_id.clone().into();
206   Ok(Activity::insert(pool, ap_id, activity, local, Some(sensitive)).await?)
207 }
208
209 /// Common methods provided by ActivityPub actors (community and person). Not all methods are
210 /// implemented by all actors.
211 pub trait ActorType: Actor + ApubObject {
212   fn actor_id(&self) -> Url;
213
214   fn private_key(&self) -> Option<String>;
215
216   fn get_public_key(&self) -> PublicKey {
217     PublicKey::new_main_key(self.actor_id(), self.public_key().to_string())
218   }
219 }
220
221 #[async_trait::async_trait(?Send)]
222 pub trait SendActivity {
223   type Response;
224
225   async fn send_activity(
226     _request: &Self,
227     _response: &Self::Response,
228     _context: &LemmyContext,
229   ) -> Result<(), LemmyError> {
230     Ok(())
231   }
232 }