]> Untitled Git - lemmy.git/blob - crates/apub/src/lib.rs
A first pass.
[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     person::Person as DbPerson,
35     post::Post,
36     private_message::PrivateMessage,
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 person
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: &DbPerson, context: &LemmyContext)
125     -> Result<(), LemmyError>;
126   async fn send_update(&self, creator: &DbPerson, context: &LemmyContext)
127     -> Result<(), LemmyError>;
128   async fn send_delete(&self, creator: &DbPerson, context: &LemmyContext)
129     -> Result<(), LemmyError>;
130   async fn send_undo_delete(
131     &self,
132     creator: &DbPerson,
133     context: &LemmyContext,
134   ) -> Result<(), LemmyError>;
135   async fn send_remove(&self, mod_: &DbPerson, context: &LemmyContext) -> Result<(), LemmyError>;
136   async fn send_undo_remove(
137     &self,
138     mod_: &DbPerson,
139     context: &LemmyContext,
140   ) -> Result<(), LemmyError>;
141 }
142
143 #[async_trait::async_trait(?Send)]
144 pub trait ApubLikeableType {
145   async fn send_like(&self, creator: &DbPerson, context: &LemmyContext) -> Result<(), LemmyError>;
146   async fn send_dislike(
147     &self,
148     creator: &DbPerson,
149     context: &LemmyContext,
150   ) -> Result<(), LemmyError>;
151   async fn send_undo_like(
152     &self,
153     creator: &DbPerson,
154     context: &LemmyContext,
155   ) -> Result<(), LemmyError>;
156 }
157
158 /// Common methods provided by ActivityPub actors (community and person). Not all methods are
159 /// implemented by all actors.
160 #[async_trait::async_trait(?Send)]
161 pub trait ActorType {
162   fn is_local(&self) -> bool;
163   fn actor_id(&self) -> Url;
164
165   // TODO: every actor should have a public key, so this shouldnt be an option (needs to be fixed in db)
166   fn public_key(&self) -> Option<String>;
167   fn private_key(&self) -> Option<String>;
168
169   async fn send_follow(
170     &self,
171     follow_actor_id: &Url,
172     context: &LemmyContext,
173   ) -> Result<(), LemmyError>;
174   async fn send_unfollow(
175     &self,
176     follow_actor_id: &Url,
177     context: &LemmyContext,
178   ) -> Result<(), LemmyError>;
179
180   async fn send_accept_follow(
181     &self,
182     follow: Follow,
183     context: &LemmyContext,
184   ) -> Result<(), LemmyError>;
185
186   async fn send_delete(&self, context: &LemmyContext) -> Result<(), LemmyError>;
187   async fn send_undo_delete(&self, context: &LemmyContext) -> Result<(), LemmyError>;
188
189   async fn send_remove(&self, context: &LemmyContext) -> Result<(), LemmyError>;
190   async fn send_undo_remove(&self, context: &LemmyContext) -> Result<(), LemmyError>;
191
192   async fn send_announce(
193     &self,
194     activity: AnyBase,
195     context: &LemmyContext,
196   ) -> Result<(), LemmyError>;
197
198   /// For a given community, returns the inboxes of all followers.
199   async fn get_follower_inboxes(&self, pool: &DbPool) -> Result<Vec<Url>, LemmyError>;
200
201   fn get_shared_inbox_or_inbox_url(&self) -> Url;
202
203   /// Outbox URL is not generally used by Lemmy, so it can be generated on the fly (but only for
204   /// local actors).
205   fn get_outbox_url(&self) -> Result<Url, LemmyError> {
206     if !self.is_local() {
207       return Err(anyhow!("get_outbox_url() called for remote actor").into());
208     }
209     Ok(Url::parse(&format!("{}/outbox", &self.actor_id()))?)
210   }
211
212   fn get_public_key_ext(&self) -> Result<PublicKeyExtension, LemmyError> {
213     Ok(
214       PublicKey {
215         id: format!("{}#main-key", self.actor_id()),
216         owner: self.actor_id(),
217         public_key_pem: self.public_key().context(location_info!())?,
218       }
219       .to_ext(),
220     )
221   }
222 }
223
224 pub enum EndpointType {
225   Community,
226   Person,
227   Post,
228   Comment,
229   PrivateMessage,
230 }
231
232 /// Generates the ActivityPub ID for a given object type and ID.
233 pub fn generate_apub_endpoint(
234   endpoint_type: EndpointType,
235   name: &str,
236 ) -> Result<DbUrl, ParseError> {
237   let point = match endpoint_type {
238     EndpointType::Community => "c",
239     EndpointType::Person => "u",
240     EndpointType::Post => "post",
241     EndpointType::Comment => "comment",
242     EndpointType::PrivateMessage => "private_message",
243   };
244
245   Ok(
246     Url::parse(&format!(
247       "{}/{}/{}",
248       Settings::get().get_protocol_and_hostname(),
249       point,
250       name
251     ))?
252     .into(),
253   )
254 }
255
256 pub fn generate_followers_url(actor_id: &DbUrl) -> Result<DbUrl, ParseError> {
257   Ok(Url::parse(&format!("{}/followers", actor_id))?.into())
258 }
259
260 pub fn generate_inbox_url(actor_id: &DbUrl) -> Result<DbUrl, ParseError> {
261   Ok(Url::parse(&format!("{}/inbox", actor_id))?.into())
262 }
263
264 pub fn generate_shared_inbox_url(actor_id: &DbUrl) -> Result<DbUrl, LemmyError> {
265   let actor_id = actor_id.clone().into_inner();
266   let url = format!(
267     "{}://{}{}/inbox",
268     &actor_id.scheme(),
269     &actor_id.host_str().context(location_info!())?,
270     if let Some(port) = actor_id.port() {
271       format!(":{}", port)
272     } else {
273       "".to_string()
274     },
275   );
276   Ok(Url::parse(&url)?.into())
277 }
278
279 /// Store a sent or received activity in the database, for logging purposes. These records are not
280 /// persistent.
281 pub(crate) async fn insert_activity<T>(
282   ap_id: &Url,
283   activity: T,
284   local: bool,
285   sensitive: bool,
286   pool: &DbPool,
287 ) -> Result<(), LemmyError>
288 where
289   T: Serialize + std::fmt::Debug + Send + 'static,
290 {
291   let ap_id = ap_id.to_owned().into();
292   blocking(pool, move |conn| {
293     Activity::insert(conn, ap_id, &activity, local, sensitive)
294   })
295   .await??;
296   Ok(())
297 }
298
299 pub(crate) enum PostOrComment {
300   Comment(Box<Comment>),
301   Post(Box<Post>),
302 }
303
304 /// Tries to find a post or comment in the local database, without any network requests.
305 /// This is used to handle deletions and removals, because in case we dont have the object, we can
306 /// simply ignore the activity.
307 pub(crate) async fn find_post_or_comment_by_id(
308   context: &LemmyContext,
309   apub_id: Url,
310 ) -> Result<PostOrComment, LemmyError> {
311   let ap_id = apub_id.clone();
312   let post = blocking(context.pool(), move |conn| {
313     Post::read_from_apub_id(conn, &ap_id.into())
314   })
315   .await?;
316   if let Ok(p) = post {
317     return Ok(PostOrComment::Post(Box::new(p)));
318   }
319
320   let ap_id = apub_id.clone();
321   let comment = blocking(context.pool(), move |conn| {
322     Comment::read_from_apub_id(conn, &ap_id.into())
323   })
324   .await?;
325   if let Ok(c) = comment {
326     return Ok(PostOrComment::Comment(Box::new(c)));
327   }
328
329   Err(NotFound.into())
330 }
331
332 pub(crate) enum Object {
333   Comment(Box<Comment>),
334   Post(Box<Post>),
335   Community(Box<Community>),
336   Person(Box<DbPerson>),
337   PrivateMessage(Box<PrivateMessage>),
338 }
339
340 pub(crate) async fn find_object_by_id(
341   context: &LemmyContext,
342   apub_id: Url,
343 ) -> Result<Object, LemmyError> {
344   let ap_id = apub_id.clone();
345   if let Ok(pc) = find_post_or_comment_by_id(context, ap_id.to_owned()).await {
346     return Ok(match pc {
347       PostOrComment::Post(p) => Object::Post(Box::new(*p)),
348       PostOrComment::Comment(c) => Object::Comment(Box::new(*c)),
349     });
350   }
351
352   let ap_id = apub_id.clone();
353   let person = blocking(context.pool(), move |conn| {
354     DbPerson::read_from_apub_id(conn, &ap_id.into())
355   })
356   .await?;
357   if let Ok(u) = person {
358     return Ok(Object::Person(Box::new(u)));
359   }
360
361   let ap_id = apub_id.clone();
362   let community = blocking(context.pool(), move |conn| {
363     Community::read_from_apub_id(conn, &ap_id.into())
364   })
365   .await?;
366   if let Ok(c) = community {
367     return Ok(Object::Community(Box::new(c)));
368   }
369
370   let private_message = blocking(context.pool(), move |conn| {
371     PrivateMessage::read_from_apub_id(conn, &apub_id.into())
372   })
373   .await?;
374   if let Ok(pm) = private_message {
375     return Ok(Object::PrivateMessage(Box::new(pm)));
376   }
377
378   Err(NotFound.into())
379 }