]> Untitled Git - lemmy.git/blob - crates/apub/src/lib.rs
Merge pull request 'Move routes into separate crate to speed up compilation' (#166...
[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 inbox;
10 pub mod objects;
11 pub mod routes;
12
13 use crate::extensions::{
14   group_extensions::GroupExtension,
15   page_extension::PageExtension,
16   signatures::{PublicKey, PublicKeyExtension},
17 };
18 use activitystreams::{
19   activity::Follow,
20   actor::{ApActor, Group, Person},
21   base::AnyBase,
22   object::{ApObject, Note, Page},
23 };
24 use activitystreams_ext::{Ext1, Ext2};
25 use anyhow::{anyhow, Context};
26 use diesel::NotFound;
27 use lemmy_db_queries::{source::activity::Activity_, ApubObject, DbPool};
28 use lemmy_db_schema::source::{
29   activity::Activity,
30   comment::Comment,
31   community::Community,
32   post::Post,
33   private_message::PrivateMessage,
34   user::User_,
35 };
36 use lemmy_structs::blocking;
37 use lemmy_utils::{location_info, settings::Settings, LemmyError};
38 use lemmy_websocket::LemmyContext;
39 use serde::Serialize;
40 use std::net::IpAddr;
41 use url::{ParseError, Url};
42
43 /// Activitystreams type for community
44 type GroupExt = Ext2<ApActor<ApObject<Group>>, GroupExtension, PublicKeyExtension>;
45 /// Activitystreams type for user
46 type PersonExt = Ext1<ApActor<ApObject<Person>>, PublicKeyExtension>;
47 /// Activitystreams type for post
48 type PageExt = Ext1<ApObject<Page>, PageExtension>;
49 type NoteExt = ApObject<Note>;
50
51 pub static APUB_JSON_CONTENT_TYPE: &str = "application/activity+json";
52
53 /// Checks if the ID is allowed for sending or receiving.
54 ///
55 /// In particular, it checks for:
56 /// - federation being enabled (if its disabled, only local URLs are allowed)
57 /// - the correct scheme (either http or https)
58 /// - URL being in the allowlist (if it is active)
59 /// - URL not being in the blocklist (if it is active)
60 ///
61 /// Note that only one of allowlist and blacklist can be enabled, not both.
62 fn check_is_apub_id_valid(apub_id: &Url) -> Result<(), LemmyError> {
63   let settings = Settings::get();
64   let domain = apub_id.domain().context(location_info!())?.to_string();
65   let local_instance = settings.get_hostname_without_port()?;
66
67   if !settings.federation.enabled {
68     return if domain == local_instance {
69       Ok(())
70     } else {
71       Err(
72         anyhow!(
73           "Trying to connect with {}, but federation is disabled",
74           domain
75         )
76         .into(),
77       )
78     };
79   }
80
81   let host = apub_id.host_str().context(location_info!())?;
82   let host_as_ip = host.parse::<IpAddr>();
83   if host == "localhost" || host_as_ip.is_ok() {
84     return Err(anyhow!("invalid hostname {}: {}", host, apub_id).into());
85   }
86
87   if apub_id.scheme() != Settings::get().get_protocol_string() {
88     return Err(anyhow!("invalid apub id scheme {}: {}", apub_id.scheme(), apub_id).into());
89   }
90
91   let mut allowed_instances = Settings::get().get_allowed_instances();
92   let blocked_instances = Settings::get().get_blocked_instances();
93   if allowed_instances.is_empty() && blocked_instances.is_empty() {
94     Ok(())
95   } else if !allowed_instances.is_empty() {
96     // need to allow this explicitly because apub receive might contain objects from our local
97     // instance. split is needed to remove the port in our federation test setup.
98     allowed_instances.push(local_instance);
99
100     if allowed_instances.contains(&domain) {
101       Ok(())
102     } else {
103       Err(anyhow!("{} not in federation allowlist", domain).into())
104     }
105   } else if !blocked_instances.is_empty() {
106     if blocked_instances.contains(&domain) {
107       Err(anyhow!("{} is in federation blocklist", domain).into())
108     } else {
109       Ok(())
110     }
111   } else {
112     panic!("Invalid config, both allowed_instances and blocked_instances are specified");
113   }
114 }
115
116 /// Common functions for ActivityPub objects, which are implemented by most (but not all) objects
117 /// and actors in Lemmy.
118 #[async_trait::async_trait(?Send)]
119 pub trait ApubObjectType {
120   async fn send_create(&self, creator: &User_, context: &LemmyContext) -> Result<(), LemmyError>;
121   async fn send_update(&self, creator: &User_, context: &LemmyContext) -> Result<(), LemmyError>;
122   async fn send_delete(&self, creator: &User_, context: &LemmyContext) -> Result<(), LemmyError>;
123   async fn send_undo_delete(
124     &self,
125     creator: &User_,
126     context: &LemmyContext,
127   ) -> Result<(), LemmyError>;
128   async fn send_remove(&self, mod_: &User_, context: &LemmyContext) -> Result<(), LemmyError>;
129   async fn send_undo_remove(&self, mod_: &User_, context: &LemmyContext) -> Result<(), LemmyError>;
130 }
131
132 #[async_trait::async_trait(?Send)]
133 pub trait ApubLikeableType {
134   async fn send_like(&self, creator: &User_, context: &LemmyContext) -> Result<(), LemmyError>;
135   async fn send_dislike(&self, creator: &User_, context: &LemmyContext) -> Result<(), LemmyError>;
136   async fn send_undo_like(&self, creator: &User_, context: &LemmyContext)
137     -> Result<(), LemmyError>;
138 }
139
140 /// Common methods provided by ActivityPub actors (community and user). Not all methods are
141 /// implemented by all actors.
142 #[async_trait::async_trait(?Send)]
143 pub trait ActorType {
144   fn is_local(&self) -> bool;
145   fn actor_id(&self) -> Url;
146
147   // TODO: every actor should have a public key, so this shouldnt be an option (needs to be fixed in db)
148   fn public_key(&self) -> Option<String>;
149   fn private_key(&self) -> Option<String>;
150
151   async fn send_follow(
152     &self,
153     follow_actor_id: &Url,
154     context: &LemmyContext,
155   ) -> Result<(), LemmyError>;
156   async fn send_unfollow(
157     &self,
158     follow_actor_id: &Url,
159     context: &LemmyContext,
160   ) -> Result<(), LemmyError>;
161
162   async fn send_accept_follow(
163     &self,
164     follow: Follow,
165     context: &LemmyContext,
166   ) -> Result<(), LemmyError>;
167
168   async fn send_delete(&self, context: &LemmyContext) -> Result<(), LemmyError>;
169   async fn send_undo_delete(&self, context: &LemmyContext) -> Result<(), LemmyError>;
170
171   async fn send_remove(&self, context: &LemmyContext) -> Result<(), LemmyError>;
172   async fn send_undo_remove(&self, context: &LemmyContext) -> Result<(), LemmyError>;
173
174   async fn send_announce(
175     &self,
176     activity: AnyBase,
177     context: &LemmyContext,
178   ) -> Result<(), LemmyError>;
179
180   /// For a given community, returns the inboxes of all followers.
181   async fn get_follower_inboxes(&self, pool: &DbPool) -> Result<Vec<Url>, LemmyError>;
182
183   fn get_shared_inbox_or_inbox_url(&self) -> Url;
184
185   /// Outbox URL is not generally used by Lemmy, so it can be generated on the fly (but only for
186   /// local actors).
187   fn get_outbox_url(&self) -> Result<Url, LemmyError> {
188     if !self.is_local() {
189       return Err(anyhow!("get_outbox_url() called for remote actor").into());
190     }
191     Ok(Url::parse(&format!("{}/outbox", &self.actor_id()))?)
192   }
193
194   fn get_public_key_ext(&self) -> Result<PublicKeyExtension, LemmyError> {
195     Ok(
196       PublicKey {
197         id: format!("{}#main-key", self.actor_id()),
198         owner: self.actor_id(),
199         public_key_pem: self.public_key().context(location_info!())?,
200       }
201       .to_ext(),
202     )
203   }
204 }
205
206 pub enum EndpointType {
207   Community,
208   User,
209   Post,
210   Comment,
211   PrivateMessage,
212 }
213
214 /// Generates the ActivityPub ID for a given object type and ID.
215 pub fn generate_apub_endpoint(
216   endpoint_type: EndpointType,
217   name: &str,
218 ) -> Result<lemmy_db_schema::Url, ParseError> {
219   let point = match endpoint_type {
220     EndpointType::Community => "c",
221     EndpointType::User => "u",
222     EndpointType::Post => "post",
223     EndpointType::Comment => "comment",
224     EndpointType::PrivateMessage => "private_message",
225   };
226
227   Ok(
228     Url::parse(&format!(
229       "{}/{}/{}",
230       Settings::get().get_protocol_and_hostname(),
231       point,
232       name
233     ))?
234     .into(),
235   )
236 }
237
238 pub fn generate_followers_url(
239   actor_id: &lemmy_db_schema::Url,
240 ) -> Result<lemmy_db_schema::Url, ParseError> {
241   Ok(Url::parse(&format!("{}/followers", actor_id))?.into())
242 }
243
244 pub fn generate_inbox_url(
245   actor_id: &lemmy_db_schema::Url,
246 ) -> Result<lemmy_db_schema::Url, ParseError> {
247   Ok(Url::parse(&format!("{}/inbox", actor_id))?.into())
248 }
249
250 pub fn generate_shared_inbox_url(
251   actor_id: &lemmy_db_schema::Url,
252 ) -> Result<lemmy_db_schema::Url, LemmyError> {
253   let actor_id = actor_id.clone().into_inner();
254   let url = format!(
255     "{}://{}{}/inbox",
256     &actor_id.scheme(),
257     &actor_id.host_str().context(location_info!())?,
258     if let Some(port) = actor_id.port() {
259       format!(":{}", port)
260     } else {
261       "".to_string()
262     },
263   );
264   Ok(Url::parse(&url)?.into())
265 }
266
267 /// Store a sent or received activity in the database, for logging purposes. These records are not
268 /// persistent.
269 pub(crate) async fn insert_activity<T>(
270   ap_id: &Url,
271   activity: T,
272   local: bool,
273   sensitive: bool,
274   pool: &DbPool,
275 ) -> Result<(), LemmyError>
276 where
277   T: Serialize + std::fmt::Debug + Send + 'static,
278 {
279   let ap_id = ap_id.to_string();
280   blocking(pool, move |conn| {
281     Activity::insert(conn, ap_id, &activity, local, sensitive)
282   })
283   .await??;
284   Ok(())
285 }
286
287 pub(crate) enum PostOrComment {
288   Comment(Comment),
289   Post(Post),
290 }
291
292 /// Tries to find a post or comment in the local database, without any network requests.
293 /// This is used to handle deletions and removals, because in case we dont have the object, we can
294 /// simply ignore the activity.
295 pub(crate) async fn find_post_or_comment_by_id(
296   context: &LemmyContext,
297   apub_id: Url,
298 ) -> Result<PostOrComment, LemmyError> {
299   let ap_id = apub_id.clone();
300   let post = blocking(context.pool(), move |conn| {
301     Post::read_from_apub_id(conn, &ap_id.into())
302   })
303   .await?;
304   if let Ok(p) = post {
305     return Ok(PostOrComment::Post(p));
306   }
307
308   let ap_id = apub_id.clone();
309   let comment = blocking(context.pool(), move |conn| {
310     Comment::read_from_apub_id(conn, &ap_id.into())
311   })
312   .await?;
313   if let Ok(c) = comment {
314     return Ok(PostOrComment::Comment(c));
315   }
316
317   Err(NotFound.into())
318 }
319
320 pub(crate) enum Object {
321   Comment(Comment),
322   Post(Post),
323   Community(Community),
324   User(User_),
325   PrivateMessage(PrivateMessage),
326 }
327
328 pub(crate) async fn find_object_by_id(
329   context: &LemmyContext,
330   apub_id: Url,
331 ) -> Result<Object, LemmyError> {
332   let ap_id = apub_id.clone();
333   if let Ok(pc) = find_post_or_comment_by_id(context, ap_id.to_owned()).await {
334     return Ok(match pc {
335       PostOrComment::Post(p) => Object::Post(p),
336       PostOrComment::Comment(c) => Object::Comment(c),
337     });
338   }
339
340   let ap_id = apub_id.clone();
341   let user = blocking(context.pool(), move |conn| {
342     User_::read_from_apub_id(conn, &ap_id.into())
343   })
344   .await?;
345   if let Ok(u) = user {
346     return Ok(Object::User(u));
347   }
348
349   let ap_id = apub_id.clone();
350   let community = blocking(context.pool(), move |conn| {
351     Community::read_from_apub_id(conn, &ap_id.into())
352   })
353   .await?;
354   if let Ok(c) = community {
355     return Ok(Object::Community(c));
356   }
357
358   let private_message = blocking(context.pool(), move |conn| {
359     PrivateMessage::read_from_apub_id(conn, &apub_id.into())
360   })
361   .await?;
362   if let Ok(pm) = private_message {
363     return Ok(Object::PrivateMessage(pm));
364   }
365
366   Err(NotFound.into())
367 }