]> Untitled Git - lemmy.git/blob - crates/apub/src/lib.rs
Rewrite voting (#1685)
[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_delete(&self, creator: &DbPerson, context: &LemmyContext)
136     -> Result<(), LemmyError>;
137   async fn send_undo_delete(
138     &self,
139     creator: &DbPerson,
140     context: &LemmyContext,
141   ) -> Result<(), LemmyError>;
142   async fn send_remove(&self, mod_: &DbPerson, context: &LemmyContext) -> Result<(), LemmyError>;
143   async fn send_undo_remove(
144     &self,
145     mod_: &DbPerson,
146     context: &LemmyContext,
147   ) -> Result<(), LemmyError>;
148 }
149
150 /// Common methods provided by ActivityPub actors (community and person). Not all methods are
151 /// implemented by all actors.
152 pub trait ActorType {
153   fn is_local(&self) -> bool;
154   fn actor_id(&self) -> Url;
155   fn name(&self) -> String;
156
157   // TODO: every actor should have a public key, so this shouldnt be an option (needs to be fixed in db)
158   fn public_key(&self) -> Option<String>;
159   fn private_key(&self) -> Option<String>;
160
161   fn get_shared_inbox_or_inbox_url(&self) -> Url;
162
163   /// Outbox URL is not generally used by Lemmy, so it can be generated on the fly (but only for
164   /// local actors).
165   fn get_outbox_url(&self) -> Result<Url, LemmyError> {
166     /* TODO
167     if !self.is_local() {
168       return Err(anyhow!("get_outbox_url() called for remote actor").into());
169     }
170     */
171     Ok(Url::parse(&format!("{}/outbox", &self.actor_id()))?)
172   }
173
174   fn get_public_key_ext(&self) -> Result<PublicKeyExtension, LemmyError> {
175     Ok(
176       PublicKey {
177         id: format!("{}#main-key", self.actor_id()),
178         owner: self.actor_id(),
179         public_key_pem: self.public_key().context(location_info!())?,
180       }
181       .to_ext(),
182     )
183   }
184 }
185
186 #[async_trait::async_trait(?Send)]
187 pub trait CommunityType {
188   fn followers_url(&self) -> Url;
189   async fn get_follower_inboxes(&self, pool: &DbPool) -> Result<Vec<Url>, LemmyError>;
190   async fn send_accept_follow(
191     &self,
192     follow: Follow,
193     context: &LemmyContext,
194   ) -> Result<(), LemmyError>;
195
196   async fn send_update(&self, mod_: Person, context: &LemmyContext) -> Result<(), LemmyError>;
197   async fn send_delete(&self, mod_: Person, context: &LemmyContext) -> Result<(), LemmyError>;
198   async fn send_undo_delete(&self, mod_: Person, context: &LemmyContext) -> Result<(), LemmyError>;
199
200   async fn send_remove(&self, context: &LemmyContext) -> Result<(), LemmyError>;
201   async fn send_undo_remove(&self, context: &LemmyContext) -> Result<(), LemmyError>;
202
203   async fn send_announce(
204     &self,
205     activity: AnyBase,
206     object: Option<Url>,
207     context: &LemmyContext,
208   ) -> Result<(), LemmyError>;
209
210   async fn send_add_mod(
211     &self,
212     actor: &Person,
213     added_mod: Person,
214     context: &LemmyContext,
215   ) -> Result<(), LemmyError>;
216   async fn send_remove_mod(
217     &self,
218     actor: &Person,
219     removed_mod: Person,
220     context: &LemmyContext,
221   ) -> Result<(), LemmyError>;
222
223   async fn send_block_user(
224     &self,
225     actor: &Person,
226     blocked_user: Person,
227     context: &LemmyContext,
228   ) -> Result<(), LemmyError>;
229   async fn send_undo_block_user(
230     &self,
231     actor: &Person,
232     blocked_user: Person,
233     context: &LemmyContext,
234   ) -> Result<(), LemmyError>;
235 }
236
237 #[async_trait::async_trait(?Send)]
238 pub trait UserType {
239   async fn send_follow(
240     &self,
241     follow_actor_id: &Url,
242     context: &LemmyContext,
243   ) -> Result<(), LemmyError>;
244   async fn send_unfollow(
245     &self,
246     follow_actor_id: &Url,
247     context: &LemmyContext,
248   ) -> Result<(), LemmyError>;
249 }
250
251 pub enum EndpointType {
252   Community,
253   Person,
254   Post,
255   Comment,
256   PrivateMessage,
257 }
258
259 /// Generates an apub endpoint for a given domain, IE xyz.tld
260 pub fn generate_apub_endpoint_for_domain(
261   endpoint_type: EndpointType,
262   name: &str,
263   domain: &str,
264 ) -> Result<DbUrl, ParseError> {
265   let point = match endpoint_type {
266     EndpointType::Community => "c",
267     EndpointType::Person => "u",
268     EndpointType::Post => "post",
269     EndpointType::Comment => "comment",
270     EndpointType::PrivateMessage => "private_message",
271   };
272
273   Ok(Url::parse(&format!("{}/{}/{}", domain, point, name))?.into())
274 }
275
276 /// Generates the ActivityPub ID for a given object type and ID.
277 pub fn generate_apub_endpoint(
278   endpoint_type: EndpointType,
279   name: &str,
280 ) -> Result<DbUrl, ParseError> {
281   generate_apub_endpoint_for_domain(
282     endpoint_type,
283     name,
284     &Settings::get().get_protocol_and_hostname(),
285   )
286 }
287
288 pub fn generate_followers_url(actor_id: &DbUrl) -> Result<DbUrl, ParseError> {
289   Ok(Url::parse(&format!("{}/followers", actor_id))?.into())
290 }
291
292 pub fn generate_inbox_url(actor_id: &DbUrl) -> Result<DbUrl, ParseError> {
293   Ok(Url::parse(&format!("{}/inbox", actor_id))?.into())
294 }
295
296 pub fn generate_shared_inbox_url(actor_id: &DbUrl) -> Result<DbUrl, LemmyError> {
297   let actor_id: Url = actor_id.clone().into();
298   let url = format!(
299     "{}://{}{}/inbox",
300     &actor_id.scheme(),
301     &actor_id.host_str().context(location_info!())?,
302     if let Some(port) = actor_id.port() {
303       format!(":{}", port)
304     } else {
305       "".to_string()
306     },
307   );
308   Ok(Url::parse(&url)?.into())
309 }
310
311 pub fn generate_moderators_url(community_id: &DbUrl) -> Result<DbUrl, LemmyError> {
312   Ok(Url::parse(&format!("{}/moderators", community_id))?.into())
313 }
314
315 /// Takes in a shortname of the type dessalines@xyz.tld or dessalines (assumed to be local), and outputs the actor id.
316 /// Used in the API for communities and users.
317 pub fn build_actor_id_from_shortname(
318   endpoint_type: EndpointType,
319   short_name: &str,
320 ) -> Result<DbUrl, ParseError> {
321   let split = short_name.split('@').collect::<Vec<&str>>();
322
323   let name = split[0];
324
325   // If there's no @, its local
326   let domain = if split.len() == 1 {
327     Settings::get().get_protocol_and_hostname()
328   } else {
329     format!("{}://{}", Settings::get().get_protocol_string(), split[1])
330   };
331
332   generate_apub_endpoint_for_domain(endpoint_type, name, &domain)
333 }
334
335 /// Store a sent or received activity in the database, for logging purposes. These records are not
336 /// persistent.
337 pub async fn insert_activity<T>(
338   ap_id: &Url,
339   activity: T,
340   local: bool,
341   sensitive: bool,
342   pool: &DbPool,
343 ) -> Result<(), LemmyError>
344 where
345   T: Serialize + std::fmt::Debug + Send + 'static,
346 {
347   let ap_id = ap_id.to_owned().into();
348   blocking(pool, move |conn| {
349     Activity::insert(conn, ap_id, &activity, local, sensitive)
350   })
351   .await??;
352   Ok(())
353 }
354
355 pub enum PostOrComment {
356   Comment(Box<Comment>),
357   Post(Box<Post>),
358 }
359
360 impl PostOrComment {
361   pub(crate) fn ap_id(&self) -> Url {
362     match self {
363       PostOrComment::Post(p) => p.ap_id.clone(),
364       PostOrComment::Comment(c) => c.ap_id.clone(),
365     }
366     .into()
367   }
368 }
369
370 /// Tries to find a post or comment in the local database, without any network requests.
371 /// This is used to handle deletions and removals, because in case we dont have the object, we can
372 /// simply ignore the activity.
373 pub async fn find_post_or_comment_by_id(
374   context: &LemmyContext,
375   apub_id: Url,
376 ) -> Result<PostOrComment, LemmyError> {
377   let ap_id = apub_id.clone();
378   let post = blocking(context.pool(), move |conn| {
379     Post::read_from_apub_id(conn, &ap_id.into())
380   })
381   .await?;
382   if let Ok(p) = post {
383     return Ok(PostOrComment::Post(Box::new(p)));
384   }
385
386   let ap_id = apub_id.clone();
387   let comment = blocking(context.pool(), move |conn| {
388     Comment::read_from_apub_id(conn, &ap_id.into())
389   })
390   .await?;
391   if let Ok(c) = comment {
392     return Ok(PostOrComment::Comment(Box::new(c)));
393   }
394
395   Err(NotFound.into())
396 }
397
398 #[derive(Debug)]
399 pub enum Object {
400   Comment(Box<Comment>),
401   Post(Box<Post>),
402   Community(Box<Community>),
403   Person(Box<DbPerson>),
404   PrivateMessage(Box<PrivateMessage>),
405 }
406
407 pub async fn find_object_by_id(context: &LemmyContext, apub_id: Url) -> Result<Object, LemmyError> {
408   let ap_id = apub_id.clone();
409   if let Ok(pc) = find_post_or_comment_by_id(context, ap_id.to_owned()).await {
410     return Ok(match pc {
411       PostOrComment::Post(p) => Object::Post(Box::new(*p)),
412       PostOrComment::Comment(c) => Object::Comment(Box::new(*c)),
413     });
414   }
415
416   let ap_id = apub_id.clone();
417   let person = blocking(context.pool(), move |conn| {
418     DbPerson::read_from_apub_id(conn, &ap_id.into())
419   })
420   .await?;
421   if let Ok(u) = person {
422     return Ok(Object::Person(Box::new(u)));
423   }
424
425   let ap_id = apub_id.clone();
426   let community = blocking(context.pool(), move |conn| {
427     Community::read_from_apub_id(conn, &ap_id.into())
428   })
429   .await?;
430   if let Ok(c) = community {
431     return Ok(Object::Community(Box::new(c)));
432   }
433
434   let private_message = blocking(context.pool(), move |conn| {
435     PrivateMessage::read_from_apub_id(conn, &apub_id.into())
436   })
437   .await?;
438   if let Ok(pm) = private_message {
439     return Ok(Object::PrivateMessage(Box::new(pm)));
440   }
441
442   Err(NotFound.into())
443 }
444
445 pub async fn check_community_or_site_ban(
446   person: &Person,
447   community_id: CommunityId,
448   pool: &DbPool,
449 ) -> Result<(), LemmyError> {
450   if person.banned {
451     return Err(anyhow!("Person is banned from site").into());
452   }
453   let person_id = person.id;
454   let is_banned =
455     move |conn: &'_ _| CommunityPersonBanView::get(conn, person_id, community_id).is_ok();
456   if blocking(pool, is_banned).await? {
457     return Err(anyhow!("Person is banned from community").into());
458   }
459
460   Ok(())
461 }
462
463 pub fn get_activity_to_and_cc<T, Kind>(activity: &T) -> Vec<Url>
464 where
465   T: AsObject<Kind>,
466 {
467   let mut to_and_cc = vec![];
468   if let Some(to) = activity.to() {
469     let to = to.to_owned().unwrap_to_vec();
470     let mut to = to
471       .iter()
472       .map(|t| t.as_xsd_any_uri())
473       .flatten()
474       .map(|t| t.to_owned())
475       .collect();
476     to_and_cc.append(&mut to);
477   }
478   if let Some(cc) = activity.cc() {
479     let cc = cc.to_owned().unwrap_to_vec();
480     let mut cc = cc
481       .iter()
482       .map(|c| c.as_xsd_any_uri())
483       .flatten()
484       .map(|c| c.to_owned())
485       .collect();
486     to_and_cc.append(&mut cc);
487   }
488   to_and_cc
489 }
490
491 pub async fn get_community_from_to_or_cc<T, Kind>(
492   activity: &T,
493   context: &LemmyContext,
494   request_counter: &mut i32,
495 ) -> Result<Community, LemmyError>
496 where
497   T: AsObject<Kind>,
498 {
499   for cid in get_activity_to_and_cc(activity) {
500     let community = get_or_fetch_and_upsert_community(&cid, context, request_counter).await;
501     if community.is_ok() {
502       return community;
503     }
504   }
505   Err(NotFound.into())
506 }