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