]> Untitled Git - lemmy.git/blob - crates/apub/src/lib.rs
Merge websocket crate into api_common
[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 anyhow::Context;
10 use async_trait::async_trait;
11 use lemmy_api_common::LemmyContext;
12 use lemmy_db_schema::{
13   newtypes::DbUrl,
14   source::{activity::Activity, instance::Instance, local_site::LocalSite},
15   utils::DbPool,
16 };
17 use lemmy_utils::{error::LemmyError, location_info, settings::structs::Settings};
18 use once_cell::sync::Lazy;
19 use tokio::sync::OnceCell;
20 use url::{ParseError, Url};
21
22 pub mod activities;
23 pub(crate) mod activity_lists;
24 pub(crate) mod collections;
25 pub mod fetcher;
26 pub mod http;
27 pub(crate) mod mentions;
28 pub mod objects;
29 pub mod protocol;
30
31 const FEDERATION_HTTP_FETCH_LIMIT: i32 = 25;
32
33 static CONTEXT: Lazy<Vec<serde_json::Value>> = Lazy::new(|| {
34   serde_json::from_str(include_str!("../assets/lemmy/context.json")).expect("parse context")
35 });
36
37 // TODO: store this in context? but its only used in this crate, no need to expose it elsewhere
38 // TODO this singleton needs to be redone to account for live data.
39 async fn local_instance(context: &LemmyContext) -> &'static LocalInstance {
40   static LOCAL_INSTANCE: OnceCell<LocalInstance> = OnceCell::const_new();
41   LOCAL_INSTANCE
42     .get_or_init(|| async {
43       // Local site may be missing
44       let local_site = &LocalSite::read(context.pool()).await;
45       let worker_count = local_site
46         .as_ref()
47         .map(|l| l.federation_worker_count)
48         .unwrap_or(64) as u64;
49       let federation_debug = local_site
50         .as_ref()
51         .map(|l| l.federation_debug)
52         .unwrap_or(true);
53
54       let settings = InstanceSettings::builder()
55         .http_fetch_retry_limit(FEDERATION_HTTP_FETCH_LIMIT)
56         .worker_count(worker_count)
57         .debug(federation_debug)
58         .http_signature_compat(true)
59         .url_verifier(Box::new(VerifyUrlData(context.clone())))
60         .build()
61         .expect("configure federation");
62       LocalInstance::new(
63         context.settings().hostname.clone(),
64         context.client().clone(),
65         settings,
66       )
67     })
68     .await
69 }
70
71 #[derive(Clone)]
72 struct VerifyUrlData(LemmyContext);
73
74 #[async_trait]
75 impl UrlVerifier for VerifyUrlData {
76   async fn verify(&self, url: &Url) -> Result<(), &'static str> {
77     let local_site_data = fetch_local_site_data(self.0.pool())
78       .await
79       .expect("read local site data");
80     check_apub_id_valid(url, &local_site_data, self.0.settings())
81   }
82 }
83
84 /// Checks if the ID is allowed for sending or receiving.
85 ///
86 /// In particular, it checks for:
87 /// - federation being enabled (if its disabled, only local URLs are allowed)
88 /// - the correct scheme (either http or https)
89 /// - URL being in the allowlist (if it is active)
90 /// - URL not being in the blocklist (if it is active)
91 ///
92 /// `use_strict_allowlist` should be true only when parsing a remote community, or when parsing a
93 /// post/comment in a local community.
94 #[tracing::instrument(skip(settings, local_site_data))]
95 fn check_apub_id_valid(
96   apub_id: &Url,
97   local_site_data: &LocalSiteData,
98   settings: &Settings,
99 ) -> Result<(), &'static str> {
100   let domain = apub_id.domain().expect("apud id has domain").to_string();
101   let local_instance = settings
102     .get_hostname_without_port()
103     .expect("local hostname is valid");
104   if domain == local_instance {
105     return Ok(());
106   }
107
108   if !local_site_data
109     .local_site
110     .as_ref()
111     .map(|l| l.federation_enabled)
112     .unwrap_or(true)
113   {
114     return Err("Federation disabled");
115   }
116
117   if apub_id.scheme() != settings.get_protocol_string() {
118     return Err("Invalid protocol scheme");
119   }
120
121   if let Some(blocked) = local_site_data.blocked_instances.as_ref() {
122     if blocked.contains(&domain) {
123       return Err("Domain is blocked");
124     }
125   }
126
127   if let Some(allowed) = local_site_data.allowed_instances.as_ref() {
128     if !allowed.contains(&domain) {
129       return Err("Domain is not in allowlist");
130     }
131   }
132
133   Ok(())
134 }
135
136 #[derive(Clone)]
137 pub(crate) struct LocalSiteData {
138   local_site: Option<LocalSite>,
139   allowed_instances: Option<Vec<String>>,
140   blocked_instances: Option<Vec<String>>,
141 }
142
143 pub(crate) async fn fetch_local_site_data(
144   pool: &DbPool,
145 ) -> Result<LocalSiteData, diesel::result::Error> {
146   // LocalSite may be missing
147   let local_site = LocalSite::read(pool).await.ok();
148   let allowed = Instance::allowlist(pool).await?;
149   let blocked = Instance::blocklist(pool).await?;
150
151   // These can return empty vectors, so convert them to options
152   let allowed_instances = (!allowed.is_empty()).then_some(allowed);
153   let blocked_instances = (!blocked.is_empty()).then_some(blocked);
154
155   Ok(LocalSiteData {
156     local_site,
157     allowed_instances,
158     blocked_instances,
159   })
160 }
161
162 #[tracing::instrument(skip(settings, local_site_data))]
163 pub(crate) fn check_apub_id_valid_with_strictness(
164   apub_id: &Url,
165   is_strict: bool,
166   local_site_data: &LocalSiteData,
167   settings: &Settings,
168 ) -> Result<(), LemmyError> {
169   check_apub_id_valid(apub_id, local_site_data, settings).map_err(LemmyError::from_message)?;
170   let domain = apub_id.domain().expect("apud id has domain").to_string();
171   let local_instance = settings
172     .get_hostname_without_port()
173     .expect("local hostname is valid");
174   if domain == local_instance {
175     return Ok(());
176   }
177
178   if let Some(allowed) = local_site_data.allowed_instances.as_ref() {
179     // Only check allowlist if this is a community
180     if is_strict {
181       // need to allow this explicitly because apub receive might contain objects from our local
182       // instance.
183       let mut allowed_and_local = allowed.clone();
184       allowed_and_local.push(local_instance);
185
186       if !allowed_and_local.contains(&domain) {
187         return Err(LemmyError::from_message(
188           "Federation forbidden by strict allowlist",
189         ));
190       }
191     }
192   }
193   Ok(())
194 }
195
196 pub enum EndpointType {
197   Community,
198   Person,
199   Post,
200   Comment,
201   PrivateMessage,
202 }
203
204 /// Generates an apub endpoint for a given domain, IE xyz.tld
205 pub fn generate_local_apub_endpoint(
206   endpoint_type: EndpointType,
207   name: &str,
208   domain: &str,
209 ) -> Result<DbUrl, ParseError> {
210   let point = match endpoint_type {
211     EndpointType::Community => "c",
212     EndpointType::Person => "u",
213     EndpointType::Post => "post",
214     EndpointType::Comment => "comment",
215     EndpointType::PrivateMessage => "private_message",
216   };
217
218   Ok(Url::parse(&format!("{}/{}/{}", domain, point, name))?.into())
219 }
220
221 pub fn generate_followers_url(actor_id: &DbUrl) -> Result<DbUrl, ParseError> {
222   Ok(Url::parse(&format!("{}/followers", actor_id))?.into())
223 }
224
225 pub fn generate_inbox_url(actor_id: &DbUrl) -> Result<DbUrl, ParseError> {
226   Ok(Url::parse(&format!("{}/inbox", actor_id))?.into())
227 }
228
229 pub fn generate_site_inbox_url(actor_id: &DbUrl) -> Result<DbUrl, ParseError> {
230   let mut actor_id: Url = actor_id.clone().into();
231   actor_id.set_path("site_inbox");
232   Ok(actor_id.into())
233 }
234
235 pub fn generate_shared_inbox_url(actor_id: &DbUrl) -> Result<DbUrl, LemmyError> {
236   let actor_id: Url = actor_id.clone().into();
237   let url = format!(
238     "{}://{}{}/inbox",
239     &actor_id.scheme(),
240     &actor_id.host_str().context(location_info!())?,
241     if let Some(port) = actor_id.port() {
242       format!(":{}", port)
243     } else {
244       String::new()
245     },
246   );
247   Ok(Url::parse(&url)?.into())
248 }
249
250 pub fn generate_outbox_url(actor_id: &DbUrl) -> Result<DbUrl, ParseError> {
251   Ok(Url::parse(&format!("{}/outbox", actor_id))?.into())
252 }
253
254 fn generate_moderators_url(community_id: &DbUrl) -> Result<DbUrl, LemmyError> {
255   Ok(Url::parse(&format!("{}/moderators", community_id))?.into())
256 }
257
258 /// Store a sent or received activity in the database, for logging purposes. These records are not
259 /// persistent.
260 #[tracing::instrument(skip(pool))]
261 async fn insert_activity(
262   ap_id: &Url,
263   activity: serde_json::Value,
264   local: bool,
265   sensitive: bool,
266   pool: &DbPool,
267 ) -> Result<bool, LemmyError> {
268   let ap_id = ap_id.clone().into();
269   Ok(Activity::insert(pool, ap_id, activity, local, Some(sensitive)).await?)
270 }
271
272 /// Common methods provided by ActivityPub actors (community and person). Not all methods are
273 /// implemented by all actors.
274 pub trait ActorType: Actor + ApubObject {
275   fn actor_id(&self) -> Url;
276
277   fn private_key(&self) -> Option<String>;
278
279   fn get_public_key(&self) -> PublicKey {
280     PublicKey::new_main_key(self.actor_id(), self.public_key().to_string())
281   }
282 }