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