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