]> Untitled Git - lemmy.git/blob - crates/apub/src/lib.rs
Rewrite settings implementation. Fixes #1270 (#1433)
[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_api_structs::blocking;
28 use lemmy_db_queries::{source::activity::Activity_, ApubObject, DbPool};
29 use lemmy_db_schema::source::{
30   activity::Activity,
31   comment::Comment,
32   community::Community,
33   post::Post,
34   private_message::PrivateMessage,
35   user::User_,
36 };
37 use lemmy_utils::{location_info, settings::structs::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 allowed_instances = Settings::get().get_allowed_instances();
92   let blocked_instances = Settings::get().get_blocked_instances();
93
94   if allowed_instances.is_none() && blocked_instances.is_none() {
95     Ok(())
96   } else if let Some(mut allowed) = allowed_instances {
97     // need to allow this explicitly because apub receive might contain objects from our local
98     // instance. split is needed to remove the port in our federation test setup.
99     allowed.push(local_instance);
100
101     if allowed.contains(&domain) {
102       Ok(())
103     } else {
104       Err(anyhow!("{} not in federation allowlist", domain).into())
105     }
106   } else if let Some(blocked) = blocked_instances {
107     if blocked.contains(&domain) {
108       Err(anyhow!("{} is in federation blocklist", domain).into())
109     } else {
110       Ok(())
111     }
112   } else {
113     panic!("Invalid config, both allowed_instances and blocked_instances are specified");
114   }
115 }
116
117 /// Common functions for ActivityPub objects, which are implemented by most (but not all) objects
118 /// and actors in Lemmy.
119 #[async_trait::async_trait(?Send)]
120 pub trait ApubObjectType {
121   async fn send_create(&self, creator: &User_, context: &LemmyContext) -> Result<(), LemmyError>;
122   async fn send_update(&self, creator: &User_, context: &LemmyContext) -> Result<(), LemmyError>;
123   async fn send_delete(&self, creator: &User_, context: &LemmyContext) -> Result<(), LemmyError>;
124   async fn send_undo_delete(
125     &self,
126     creator: &User_,
127     context: &LemmyContext,
128   ) -> Result<(), LemmyError>;
129   async fn send_remove(&self, mod_: &User_, context: &LemmyContext) -> Result<(), LemmyError>;
130   async fn send_undo_remove(&self, mod_: &User_, context: &LemmyContext) -> Result<(), LemmyError>;
131 }
132
133 #[async_trait::async_trait(?Send)]
134 pub trait ApubLikeableType {
135   async fn send_like(&self, creator: &User_, context: &LemmyContext) -> Result<(), LemmyError>;
136   async fn send_dislike(&self, creator: &User_, context: &LemmyContext) -> Result<(), LemmyError>;
137   async fn send_undo_like(&self, creator: &User_, context: &LemmyContext)
138     -> Result<(), LemmyError>;
139 }
140
141 /// Common methods provided by ActivityPub actors (community and user). Not all methods are
142 /// implemented by all actors.
143 #[async_trait::async_trait(?Send)]
144 pub trait ActorType {
145   fn is_local(&self) -> bool;
146   fn actor_id(&self) -> Url;
147
148   // TODO: every actor should have a public key, so this shouldnt be an option (needs to be fixed in db)
149   fn public_key(&self) -> Option<String>;
150   fn private_key(&self) -> Option<String>;
151
152   async fn send_follow(
153     &self,
154     follow_actor_id: &Url,
155     context: &LemmyContext,
156   ) -> Result<(), LemmyError>;
157   async fn send_unfollow(
158     &self,
159     follow_actor_id: &Url,
160     context: &LemmyContext,
161   ) -> Result<(), LemmyError>;
162
163   async fn send_accept_follow(
164     &self,
165     follow: Follow,
166     context: &LemmyContext,
167   ) -> Result<(), LemmyError>;
168
169   async fn send_delete(&self, context: &LemmyContext) -> Result<(), LemmyError>;
170   async fn send_undo_delete(&self, context: &LemmyContext) -> Result<(), LemmyError>;
171
172   async fn send_remove(&self, context: &LemmyContext) -> Result<(), LemmyError>;
173   async fn send_undo_remove(&self, context: &LemmyContext) -> Result<(), LemmyError>;
174
175   async fn send_announce(
176     &self,
177     activity: AnyBase,
178     context: &LemmyContext,
179   ) -> Result<(), LemmyError>;
180
181   /// For a given community, returns the inboxes of all followers.
182   async fn get_follower_inboxes(&self, pool: &DbPool) -> Result<Vec<Url>, LemmyError>;
183
184   fn get_shared_inbox_or_inbox_url(&self) -> Url;
185
186   /// Outbox URL is not generally used by Lemmy, so it can be generated on the fly (but only for
187   /// local actors).
188   fn get_outbox_url(&self) -> Result<Url, LemmyError> {
189     if !self.is_local() {
190       return Err(anyhow!("get_outbox_url() called for remote actor").into());
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 pub enum EndpointType {
208   Community,
209   User,
210   Post,
211   Comment,
212   PrivateMessage,
213 }
214
215 /// Generates the ActivityPub ID for a given object type and ID.
216 pub fn generate_apub_endpoint(
217   endpoint_type: EndpointType,
218   name: &str,
219 ) -> Result<lemmy_db_schema::Url, ParseError> {
220   let point = match endpoint_type {
221     EndpointType::Community => "c",
222     EndpointType::User => "u",
223     EndpointType::Post => "post",
224     EndpointType::Comment => "comment",
225     EndpointType::PrivateMessage => "private_message",
226   };
227
228   Ok(
229     Url::parse(&format!(
230       "{}/{}/{}",
231       Settings::get().get_protocol_and_hostname(),
232       point,
233       name
234     ))?
235     .into(),
236   )
237 }
238
239 pub fn generate_followers_url(
240   actor_id: &lemmy_db_schema::Url,
241 ) -> Result<lemmy_db_schema::Url, ParseError> {
242   Ok(Url::parse(&format!("{}/followers", actor_id))?.into())
243 }
244
245 pub fn generate_inbox_url(
246   actor_id: &lemmy_db_schema::Url,
247 ) -> Result<lemmy_db_schema::Url, ParseError> {
248   Ok(Url::parse(&format!("{}/inbox", actor_id))?.into())
249 }
250
251 pub fn generate_shared_inbox_url(
252   actor_id: &lemmy_db_schema::Url,
253 ) -> Result<lemmy_db_schema::Url, LemmyError> {
254   let actor_id = actor_id.clone().into_inner();
255   let url = format!(
256     "{}://{}{}/inbox",
257     &actor_id.scheme(),
258     &actor_id.host_str().context(location_info!())?,
259     if let Some(port) = actor_id.port() {
260       format!(":{}", port)
261     } else {
262       "".to_string()
263     },
264   );
265   Ok(Url::parse(&url)?.into())
266 }
267
268 /// Store a sent or received activity in the database, for logging purposes. These records are not
269 /// persistent.
270 pub(crate) async fn insert_activity<T>(
271   ap_id: &Url,
272   activity: T,
273   local: bool,
274   sensitive: bool,
275   pool: &DbPool,
276 ) -> Result<(), LemmyError>
277 where
278   T: Serialize + std::fmt::Debug + Send + 'static,
279 {
280   let ap_id = ap_id.to_string();
281   blocking(pool, move |conn| {
282     Activity::insert(conn, ap_id, &activity, local, sensitive)
283   })
284   .await??;
285   Ok(())
286 }
287
288 pub(crate) enum PostOrComment {
289   Comment(Comment),
290   Post(Post),
291 }
292
293 /// Tries to find a post or comment in the local database, without any network requests.
294 /// This is used to handle deletions and removals, because in case we dont have the object, we can
295 /// simply ignore the activity.
296 pub(crate) async fn find_post_or_comment_by_id(
297   context: &LemmyContext,
298   apub_id: Url,
299 ) -> Result<PostOrComment, LemmyError> {
300   let ap_id = apub_id.clone();
301   let post = blocking(context.pool(), move |conn| {
302     Post::read_from_apub_id(conn, &ap_id.into())
303   })
304   .await?;
305   if let Ok(p) = post {
306     return Ok(PostOrComment::Post(p));
307   }
308
309   let ap_id = apub_id.clone();
310   let comment = blocking(context.pool(), move |conn| {
311     Comment::read_from_apub_id(conn, &ap_id.into())
312   })
313   .await?;
314   if let Ok(c) = comment {
315     return Ok(PostOrComment::Comment(c));
316   }
317
318   Err(NotFound.into())
319 }
320
321 pub(crate) enum Object {
322   Comment(Comment),
323   Post(Post),
324   Community(Community),
325   User(User_),
326   PrivateMessage(PrivateMessage),
327 }
328
329 pub(crate) async fn find_object_by_id(
330   context: &LemmyContext,
331   apub_id: Url,
332 ) -> Result<Object, LemmyError> {
333   let ap_id = apub_id.clone();
334   if let Ok(pc) = find_post_or_comment_by_id(context, ap_id.to_owned()).await {
335     return Ok(match pc {
336       PostOrComment::Post(p) => Object::Post(p),
337       PostOrComment::Comment(c) => Object::Comment(c),
338     });
339   }
340
341   let ap_id = apub_id.clone();
342   let user = blocking(context.pool(), move |conn| {
343     User_::read_from_apub_id(conn, &ap_id.into())
344   })
345   .await?;
346   if let Ok(u) = user {
347     return Ok(Object::User(u));
348   }
349
350   let ap_id = apub_id.clone();
351   let community = blocking(context.pool(), move |conn| {
352     Community::read_from_apub_id(conn, &ap_id.into())
353   })
354   .await?;
355   if let Ok(c) = community {
356     return Ok(Object::Community(c));
357   }
358
359   let private_message = blocking(context.pool(), move |conn| {
360     PrivateMessage::read_from_apub_id(conn, &apub_id.into())
361   })
362   .await?;
363   if let Ok(pm) = private_message {
364     return Ok(Object::PrivateMessage(pm));
365   }
366
367   Err(NotFound.into())
368 }