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