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