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