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