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