]> Untitled Git - lemmy.git/blob - crates/apub/src/lib.rs
Merge pull request 'Split lemmy_apub crate into two parts apub and apub_receive'...
[lemmy.git] / crates / apub / src / lib.rs
1 #[macro_use]
2 extern crate lazy_static;
3
4 pub mod activities;
5 pub mod activity_queue;
6 pub mod extensions;
7 pub mod fetcher;
8 pub mod objects;
9
10 use crate::extensions::{
11   group_extension::GroupExtension,
12   page_extension::PageExtension,
13   person_extension::PersonExtension,
14   signatures::{PublicKey, PublicKeyExtension},
15 };
16 use activitystreams::{
17   activity::Follow,
18   actor,
19   base::AnyBase,
20   object::{ApObject, AsObject, Note, ObjectExt, Page},
21 };
22 use activitystreams_ext::{Ext1, Ext2};
23 use anyhow::{anyhow, Context};
24 use diesel::NotFound;
25 use lemmy_api_common::blocking;
26 use lemmy_db_queries::{source::activity::Activity_, ApubObject, DbPool};
27 use lemmy_db_schema::{
28   source::{
29     activity::Activity,
30     comment::Comment,
31     community::Community,
32     person::{Person as DbPerson, Person},
33     post::Post,
34     private_message::PrivateMessage,
35   },
36   CommunityId,
37   DbUrl,
38 };
39 use lemmy_db_views_actor::community_person_ban_view::CommunityPersonBanView;
40 use lemmy_utils::{location_info, settings::structs::Settings, LemmyError};
41 use lemmy_websocket::LemmyContext;
42 use serde::Serialize;
43 use std::net::IpAddr;
44 use url::{ParseError, Url};
45
46 /// Activitystreams type for community
47 type GroupExt = Ext2<actor::ApActor<ApObject<actor::Group>>, GroupExtension, PublicKeyExtension>;
48 /// Activitystreams type for person
49 type PersonExt = Ext2<actor::ApActor<ApObject<actor::Person>>, PersonExtension, PublicKeyExtension>;
50 /// Activitystreams type for post
51 pub type PageExt = Ext1<ApObject<Page>, PageExtension>;
52 pub type NoteExt = ApObject<Note>;
53
54 pub static APUB_JSON_CONTENT_TYPE: &str = "application/activity+json";
55
56 /// Checks if the ID is allowed for sending or receiving.
57 ///
58 /// In particular, it checks for:
59 /// - federation being enabled (if its disabled, only local URLs are allowed)
60 /// - the correct scheme (either http or https)
61 /// - URL being in the allowlist (if it is active)
62 /// - URL not being in the blocklist (if it is active)
63 ///
64 /// Note that only one of allowlist and blacklist can be enabled, not both.
65 pub fn check_is_apub_id_valid(apub_id: &Url) -> Result<(), LemmyError> {
66   let settings = Settings::get();
67   let domain = apub_id.domain().context(location_info!())?.to_string();
68   let local_instance = settings.get_hostname_without_port()?;
69
70   if !settings.federation().enabled {
71     return if domain == local_instance {
72       Ok(())
73     } else {
74       Err(
75         anyhow!(
76           "Trying to connect with {}, but federation is disabled",
77           domain
78         )
79         .into(),
80       )
81     };
82   }
83
84   let host = apub_id.host_str().context(location_info!())?;
85   let host_as_ip = host.parse::<IpAddr>();
86   if host == "localhost" || host_as_ip.is_ok() {
87     return Err(anyhow!("invalid hostname {}: {}", host, apub_id).into());
88   }
89
90   if apub_id.scheme() != Settings::get().get_protocol_string() {
91     return Err(anyhow!("invalid apub id scheme {}: {}", apub_id.scheme(), apub_id).into());
92   }
93
94   let allowed_instances = Settings::get().get_allowed_instances();
95   let blocked_instances = Settings::get().get_blocked_instances();
96
97   if allowed_instances.is_none() && blocked_instances.is_none() {
98     Ok(())
99   } else if let Some(mut allowed) = allowed_instances {
100     // need to allow this explicitly because apub receive might contain objects from our local
101     // instance. split is needed to remove the port in our federation test setup.
102     allowed.push(local_instance);
103
104     if allowed.contains(&domain) {
105       Ok(())
106     } else {
107       Err(anyhow!("{} not in federation allowlist", domain).into())
108     }
109   } else if let Some(blocked) = blocked_instances {
110     if blocked.contains(&domain) {
111       Err(anyhow!("{} is in federation blocklist", domain).into())
112     } else {
113       Ok(())
114     }
115   } else {
116     panic!("Invalid config, both allowed_instances and blocked_instances are specified");
117   }
118 }
119
120 /// Common functions for ActivityPub objects, which are implemented by most (but not all) objects
121 /// and actors in Lemmy.
122 #[async_trait::async_trait(?Send)]
123 pub trait ApubObjectType {
124   async fn send_create(&self, creator: &DbPerson, context: &LemmyContext)
125     -> Result<(), LemmyError>;
126   async fn send_update(&self, creator: &DbPerson, context: &LemmyContext)
127     -> Result<(), LemmyError>;
128   async fn send_delete(&self, creator: &DbPerson, context: &LemmyContext)
129     -> Result<(), LemmyError>;
130   async fn send_undo_delete(
131     &self,
132     creator: &DbPerson,
133     context: &LemmyContext,
134   ) -> Result<(), LemmyError>;
135   async fn send_remove(&self, mod_: &DbPerson, context: &LemmyContext) -> Result<(), LemmyError>;
136   async fn send_undo_remove(
137     &self,
138     mod_: &DbPerson,
139     context: &LemmyContext,
140   ) -> Result<(), LemmyError>;
141 }
142
143 #[async_trait::async_trait(?Send)]
144 pub trait ApubLikeableType {
145   async fn send_like(&self, creator: &DbPerson, context: &LemmyContext) -> Result<(), LemmyError>;
146   async fn send_dislike(
147     &self,
148     creator: &DbPerson,
149     context: &LemmyContext,
150   ) -> Result<(), LemmyError>;
151   async fn send_undo_like(
152     &self,
153     creator: &DbPerson,
154     context: &LemmyContext,
155   ) -> Result<(), LemmyError>;
156 }
157
158 /// Common methods provided by ActivityPub actors (community and person). Not all methods are
159 /// implemented by all actors.
160 #[async_trait::async_trait(?Send)]
161 pub trait ActorType {
162   fn is_local(&self) -> bool;
163   fn actor_id(&self) -> Url;
164
165   // TODO: every actor should have a public key, so this shouldnt be an option (needs to be fixed in db)
166   fn public_key(&self) -> Option<String>;
167   fn private_key(&self) -> Option<String>;
168
169   fn get_shared_inbox_or_inbox_url(&self) -> Url;
170
171   /// Outbox URL is not generally used by Lemmy, so it can be generated on the fly (but only for
172   /// local actors).
173   fn get_outbox_url(&self) -> Result<Url, LemmyError> {
174     if !self.is_local() {
175       return Err(anyhow!("get_outbox_url() called for remote actor").into());
176     }
177     Ok(Url::parse(&format!("{}/outbox", &self.actor_id()))?)
178   }
179
180   fn get_public_key_ext(&self) -> Result<PublicKeyExtension, LemmyError> {
181     Ok(
182       PublicKey {
183         id: format!("{}#main-key", self.actor_id()),
184         owner: self.actor_id(),
185         public_key_pem: self.public_key().context(location_info!())?,
186       }
187       .to_ext(),
188     )
189   }
190 }
191
192 #[async_trait::async_trait(?Send)]
193 pub trait CommunityType {
194   async fn get_follower_inboxes(&self, pool: &DbPool) -> Result<Vec<Url>, LemmyError>;
195   async fn send_accept_follow(
196     &self,
197     follow: Follow,
198     context: &LemmyContext,
199   ) -> Result<(), LemmyError>;
200
201   async fn send_delete(&self, context: &LemmyContext) -> Result<(), LemmyError>;
202   async fn send_undo_delete(&self, context: &LemmyContext) -> Result<(), LemmyError>;
203
204   async fn send_remove(&self, context: &LemmyContext) -> Result<(), LemmyError>;
205   async fn send_undo_remove(&self, context: &LemmyContext) -> Result<(), LemmyError>;
206
207   async fn send_announce(
208     &self,
209     activity: AnyBase,
210     context: &LemmyContext,
211   ) -> Result<(), LemmyError>;
212
213   async fn send_add_mod(
214     &self,
215     actor: &Person,
216     added_mod: Person,
217     context: &LemmyContext,
218   ) -> Result<(), LemmyError>;
219   async fn send_remove_mod(
220     &self,
221     actor: &Person,
222     removed_mod: Person,
223     context: &LemmyContext,
224   ) -> Result<(), LemmyError>;
225 }
226
227 #[async_trait::async_trait(?Send)]
228 pub trait UserType {
229   async fn send_follow(
230     &self,
231     follow_actor_id: &Url,
232     context: &LemmyContext,
233   ) -> Result<(), LemmyError>;
234   async fn send_unfollow(
235     &self,
236     follow_actor_id: &Url,
237     context: &LemmyContext,
238   ) -> Result<(), LemmyError>;
239 }
240
241 pub enum EndpointType {
242   Community,
243   Person,
244   Post,
245   Comment,
246   PrivateMessage,
247 }
248
249 /// Generates the ActivityPub ID for a given object type and ID.
250 pub fn generate_apub_endpoint(
251   endpoint_type: EndpointType,
252   name: &str,
253 ) -> Result<DbUrl, ParseError> {
254   let point = match endpoint_type {
255     EndpointType::Community => "c",
256     EndpointType::Person => "u",
257     EndpointType::Post => "post",
258     EndpointType::Comment => "comment",
259     EndpointType::PrivateMessage => "private_message",
260   };
261
262   Ok(
263     Url::parse(&format!(
264       "{}/{}/{}",
265       Settings::get().get_protocol_and_hostname(),
266       point,
267       name
268     ))?
269     .into(),
270   )
271 }
272
273 pub fn generate_followers_url(actor_id: &DbUrl) -> Result<DbUrl, ParseError> {
274   Ok(Url::parse(&format!("{}/followers", actor_id))?.into())
275 }
276
277 pub fn generate_inbox_url(actor_id: &DbUrl) -> Result<DbUrl, ParseError> {
278   Ok(Url::parse(&format!("{}/inbox", actor_id))?.into())
279 }
280
281 pub fn generate_shared_inbox_url(actor_id: &DbUrl) -> Result<DbUrl, LemmyError> {
282   let actor_id = actor_id.clone().into_inner();
283   let url = format!(
284     "{}://{}{}/inbox",
285     &actor_id.scheme(),
286     &actor_id.host_str().context(location_info!())?,
287     if let Some(port) = actor_id.port() {
288       format!(":{}", port)
289     } else {
290       "".to_string()
291     },
292   );
293   Ok(Url::parse(&url)?.into())
294 }
295
296 pub fn generate_moderators_url(community_id: &DbUrl) -> Result<DbUrl, LemmyError> {
297   Ok(Url::parse(&format!("{}/moderators", community_id))?.into())
298 }
299
300 /// Store a sent or received activity in the database, for logging purposes. These records are not
301 /// persistent.
302 pub async fn insert_activity<T>(
303   ap_id: &Url,
304   activity: T,
305   local: bool,
306   sensitive: bool,
307   pool: &DbPool,
308 ) -> Result<(), LemmyError>
309 where
310   T: Serialize + std::fmt::Debug + Send + 'static,
311 {
312   let ap_id = ap_id.to_owned().into();
313   blocking(pool, move |conn| {
314     Activity::insert(conn, ap_id, &activity, local, sensitive)
315   })
316   .await??;
317   Ok(())
318 }
319
320 pub enum PostOrComment {
321   Comment(Box<Comment>),
322   Post(Box<Post>),
323 }
324
325 /// Tries to find a post or comment in the local database, without any network requests.
326 /// This is used to handle deletions and removals, because in case we dont have the object, we can
327 /// simply ignore the activity.
328 pub async fn find_post_or_comment_by_id(
329   context: &LemmyContext,
330   apub_id: Url,
331 ) -> Result<PostOrComment, LemmyError> {
332   let ap_id = apub_id.clone();
333   let post = blocking(context.pool(), move |conn| {
334     Post::read_from_apub_id(conn, &ap_id.into())
335   })
336   .await?;
337   if let Ok(p) = post {
338     return Ok(PostOrComment::Post(Box::new(p)));
339   }
340
341   let ap_id = apub_id.clone();
342   let comment = blocking(context.pool(), move |conn| {
343     Comment::read_from_apub_id(conn, &ap_id.into())
344   })
345   .await?;
346   if let Ok(c) = comment {
347     return Ok(PostOrComment::Comment(Box::new(c)));
348   }
349
350   Err(NotFound.into())
351 }
352
353 #[derive(Debug)]
354 pub(crate) enum Object {
355   Comment(Box<Comment>),
356   Post(Box<Post>),
357   Community(Box<Community>),
358   Person(Box<DbPerson>),
359   PrivateMessage(Box<PrivateMessage>),
360 }
361
362 pub(crate) async fn find_object_by_id(
363   context: &LemmyContext,
364   apub_id: Url,
365 ) -> Result<Object, LemmyError> {
366   let ap_id = apub_id.clone();
367   if let Ok(pc) = find_post_or_comment_by_id(context, ap_id.to_owned()).await {
368     return Ok(match pc {
369       PostOrComment::Post(p) => Object::Post(Box::new(*p)),
370       PostOrComment::Comment(c) => Object::Comment(Box::new(*c)),
371     });
372   }
373
374   let ap_id = apub_id.clone();
375   let person = blocking(context.pool(), move |conn| {
376     DbPerson::read_from_apub_id(conn, &ap_id.into())
377   })
378   .await?;
379   if let Ok(u) = person {
380     return Ok(Object::Person(Box::new(u)));
381   }
382
383   let ap_id = apub_id.clone();
384   let community = blocking(context.pool(), move |conn| {
385     Community::read_from_apub_id(conn, &ap_id.into())
386   })
387   .await?;
388   if let Ok(c) = community {
389     return Ok(Object::Community(Box::new(c)));
390   }
391
392   let private_message = blocking(context.pool(), move |conn| {
393     PrivateMessage::read_from_apub_id(conn, &apub_id.into())
394   })
395   .await?;
396   if let Ok(pm) = private_message {
397     return Ok(Object::PrivateMessage(Box::new(pm)));
398   }
399
400   Err(NotFound.into())
401 }
402
403 pub async fn check_community_or_site_ban(
404   person: &Person,
405   community_id: CommunityId,
406   pool: &DbPool,
407 ) -> Result<(), LemmyError> {
408   if person.banned {
409     return Err(anyhow!("Person is banned from site").into());
410   }
411   let person_id = person.id;
412   let is_banned =
413     move |conn: &'_ _| CommunityPersonBanView::get(conn, person_id, community_id).is_ok();
414   if blocking(pool, is_banned).await? {
415     return Err(anyhow!("Person is banned from community").into());
416   }
417
418   Ok(())
419 }
420
421 pub fn get_activity_to_and_cc<T, Kind>(activity: &T) -> Vec<Url>
422 where
423   T: AsObject<Kind>,
424 {
425   let mut to_and_cc = vec![];
426   if let Some(to) = activity.to() {
427     let to = to.to_owned().unwrap_to_vec();
428     let mut to = to
429       .iter()
430       .map(|t| t.as_xsd_any_uri())
431       .flatten()
432       .map(|t| t.to_owned())
433       .collect();
434     to_and_cc.append(&mut to);
435   }
436   if let Some(cc) = activity.cc() {
437     let cc = cc.to_owned().unwrap_to_vec();
438     let mut cc = cc
439       .iter()
440       .map(|c| c.as_xsd_any_uri())
441       .flatten()
442       .map(|c| c.to_owned())
443       .collect();
444     to_and_cc.append(&mut cc);
445   }
446   to_and_cc
447 }