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