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