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