]> Untitled Git - lemmy.git/blob - crates/apub/src/lib.rs
53fe7cd3fe54e79b2b38ce5278cdeab10d58c3a2
[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
49       let settings = InstanceSettings::builder()
50         .http_fetch_retry_limit(FEDERATION_HTTP_FETCH_LIMIT)
51         .worker_count(worker_count)
52         .debug(cfg!(debug_assertions))
53         .http_signature_compat(true)
54         .url_verifier(Box::new(VerifyUrlData(context.clone())))
55         .build()
56         .expect("configure federation");
57       LocalInstance::new(
58         context.settings().hostname.clone(),
59         context.client().clone(),
60         settings,
61       )
62     })
63     .await
64 }
65
66 #[derive(Clone)]
67 struct VerifyUrlData(LemmyContext);
68
69 #[async_trait]
70 impl UrlVerifier for VerifyUrlData {
71   async fn verify(&self, url: &Url) -> Result<(), &'static str> {
72     let local_site_data = fetch_local_site_data(self.0.pool())
73       .await
74       .expect("read local site data");
75     check_apub_id_valid(url, &local_site_data, self.0.settings())
76   }
77 }
78
79 /// Checks if the ID is allowed for sending or receiving.
80 ///
81 /// In particular, it checks for:
82 /// - federation being enabled (if its disabled, only local URLs are allowed)
83 /// - the correct scheme (either http or https)
84 /// - URL being in the allowlist (if it is active)
85 /// - URL not being in the blocklist (if it is active)
86 ///
87 /// `use_strict_allowlist` should be true only when parsing a remote community, or when parsing a
88 /// post/comment in a local community.
89 #[tracing::instrument(skip(settings, local_site_data))]
90 fn check_apub_id_valid(
91   apub_id: &Url,
92   local_site_data: &LocalSiteData,
93   settings: &Settings,
94 ) -> Result<(), &'static str> {
95   let domain = apub_id.domain().expect("apud id has domain").to_string();
96   let local_instance = settings
97     .get_hostname_without_port()
98     .expect("local hostname is valid");
99   if domain == local_instance {
100     return Ok(());
101   }
102
103   if !local_site_data
104     .local_site
105     .as_ref()
106     .map(|l| l.federation_enabled)
107     .unwrap_or(true)
108   {
109     return Err("Federation disabled");
110   }
111
112   if apub_id.scheme() != settings.get_protocol_string() {
113     return Err("Invalid protocol scheme");
114   }
115
116   if let Some(blocked) = local_site_data.blocked_instances.as_ref() {
117     if blocked.contains(&domain) {
118       return Err("Domain is blocked");
119     }
120   }
121
122   if let Some(allowed) = local_site_data.allowed_instances.as_ref() {
123     if !allowed.contains(&domain) {
124       return Err("Domain is not in allowlist");
125     }
126   }
127
128   Ok(())
129 }
130
131 #[derive(Clone)]
132 pub(crate) struct LocalSiteData {
133   local_site: Option<LocalSite>,
134   allowed_instances: Option<Vec<String>>,
135   blocked_instances: Option<Vec<String>>,
136 }
137
138 pub(crate) async fn fetch_local_site_data(
139   pool: &DbPool,
140 ) -> Result<LocalSiteData, diesel::result::Error> {
141   // LocalSite may be missing
142   let local_site = LocalSite::read(pool).await.ok();
143   let allowed = Instance::allowlist(pool).await?;
144   let blocked = Instance::blocklist(pool).await?;
145
146   // These can return empty vectors, so convert them to options
147   let allowed_instances = (!allowed.is_empty()).then_some(allowed);
148   let blocked_instances = (!blocked.is_empty()).then_some(blocked);
149
150   Ok(LocalSiteData {
151     local_site,
152     allowed_instances,
153     blocked_instances,
154   })
155 }
156
157 #[tracing::instrument(skip(settings, local_site_data))]
158 pub(crate) fn check_apub_id_valid_with_strictness(
159   apub_id: &Url,
160   is_strict: bool,
161   local_site_data: &LocalSiteData,
162   settings: &Settings,
163 ) -> Result<(), LemmyError> {
164   check_apub_id_valid(apub_id, local_site_data, settings).map_err(LemmyError::from_message)?;
165   let domain = apub_id.domain().expect("apud id has domain").to_string();
166   let local_instance = settings
167     .get_hostname_without_port()
168     .expect("local hostname is valid");
169   if domain == local_instance {
170     return Ok(());
171   }
172
173   if let Some(allowed) = local_site_data.allowed_instances.as_ref() {
174     // Only check allowlist if this is a community
175     if is_strict {
176       // need to allow this explicitly because apub receive might contain objects from our local
177       // instance.
178       let mut allowed_and_local = allowed.clone();
179       allowed_and_local.push(local_instance);
180
181       if !allowed_and_local.contains(&domain) {
182         return Err(LemmyError::from_message(
183           "Federation forbidden by strict allowlist",
184         ));
185       }
186     }
187   }
188   Ok(())
189 }
190
191 /// Store a sent or received activity in the database, for logging purposes. These records are not
192 /// persistent.
193 #[tracing::instrument(skip(pool))]
194 async fn insert_activity(
195   ap_id: &Url,
196   activity: serde_json::Value,
197   local: bool,
198   sensitive: bool,
199   pool: &DbPool,
200 ) -> Result<bool, LemmyError> {
201   let ap_id = ap_id.clone().into();
202   Ok(Activity::insert(pool, ap_id, activity, local, Some(sensitive)).await?)
203 }
204
205 /// Common methods provided by ActivityPub actors (community and person). Not all methods are
206 /// implemented by all actors.
207 pub trait ActorType: Actor + ApubObject {
208   fn actor_id(&self) -> Url;
209
210   fn private_key(&self) -> Option<String>;
211
212   fn get_public_key(&self) -> PublicKey {
213     PublicKey::new_main_key(self.actor_id(), self.public_key().to_string())
214   }
215 }
216
217 #[async_trait::async_trait(?Send)]
218 pub trait SendActivity {
219   type Response;
220
221   async fn send_activity(
222     _request: &Self,
223     _response: &Self::Response,
224     _context: &LemmyContext,
225   ) -> Result<(), LemmyError> {
226     Ok(())
227   }
228 }