]> Untitled Git - lemmy.git/blob - crates/apub/src/lib.rs
Rewrite remaining activities (#1712)
[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 migrations;
10 pub mod objects;
11
12 use crate::extensions::signatures::PublicKey;
13 use anyhow::{anyhow, Context};
14 use diesel::NotFound;
15 use lemmy_api_common::blocking;
16 use lemmy_db_queries::{source::activity::Activity_, ApubObject, DbPool};
17 use lemmy_db_schema::{
18   source::{
19     activity::Activity,
20     comment::Comment,
21     community::Community,
22     person::{Person as DbPerson, Person},
23     post::Post,
24     private_message::PrivateMessage,
25   },
26   CommunityId,
27   DbUrl,
28 };
29 use lemmy_db_views_actor::community_person_ban_view::CommunityPersonBanView;
30 use lemmy_utils::{location_info, settings::structs::Settings, LemmyError};
31 use lemmy_websocket::LemmyContext;
32 use serde::Serialize;
33 use std::net::IpAddr;
34 use url::{ParseError, Url};
35
36 static APUB_JSON_CONTENT_TYPE: &str = "application/activity+json";
37
38 /// Checks if the ID is allowed for sending or receiving.
39 ///
40 /// In particular, it checks for:
41 /// - federation being enabled (if its disabled, only local URLs are allowed)
42 /// - the correct scheme (either http or https)
43 /// - URL being in the allowlist (if it is active)
44 /// - URL not being in the blocklist (if it is active)
45 ///
46 pub(crate) fn check_is_apub_id_valid(
47   apub_id: &Url,
48   use_strict_allowlist: bool,
49 ) -> Result<(), LemmyError> {
50   let settings = Settings::get();
51   let domain = apub_id.domain().context(location_info!())?.to_string();
52   let local_instance = settings.get_hostname_without_port()?;
53
54   if !settings.federation.enabled {
55     return if domain == local_instance {
56       Ok(())
57     } else {
58       Err(
59         anyhow!(
60           "Trying to connect with {}, but federation is disabled",
61           domain
62         )
63         .into(),
64       )
65     };
66   }
67
68   let host = apub_id.host_str().context(location_info!())?;
69   let host_as_ip = host.parse::<IpAddr>();
70   if host == "localhost" || host_as_ip.is_ok() {
71     return Err(anyhow!("invalid hostname {}: {}", host, apub_id).into());
72   }
73
74   if apub_id.scheme() != Settings::get().get_protocol_string() {
75     return Err(anyhow!("invalid apub id scheme {}: {}", apub_id.scheme(), apub_id).into());
76   }
77
78   // TODO: might be good to put the part above in one method, and below in another
79   //       (which only gets called in apub::objects)
80   //        -> no that doesnt make sense, we still need the code below for blocklist and strict allowlist
81   if let Some(blocked) = Settings::get().federation.blocked_instances {
82     if blocked.contains(&domain) {
83       return Err(anyhow!("{} is in federation blocklist", domain).into());
84     }
85   }
86
87   if let Some(mut allowed) = Settings::get().federation.allowed_instances {
88     // Only check allowlist if this is a community, or strict allowlist is enabled.
89     let strict_allowlist = Settings::get().federation.strict_allowlist;
90     if use_strict_allowlist || strict_allowlist {
91       // need to allow this explicitly because apub receive might contain objects from our local
92       // instance.
93       allowed.push(local_instance);
94
95       if !allowed.contains(&domain) {
96         return Err(anyhow!("{} not in federation allowlist", domain).into());
97       }
98     }
99   }
100
101   Ok(())
102 }
103
104 /// Common methods provided by ActivityPub actors (community and person). Not all methods are
105 /// implemented by all actors.
106 trait ActorType {
107   fn is_local(&self) -> bool;
108   fn actor_id(&self) -> Url;
109   fn name(&self) -> String;
110
111   // TODO: every actor should have a public key, so this shouldnt be an option (needs to be fixed in db)
112   fn public_key(&self) -> Option<String>;
113   fn private_key(&self) -> Option<String>;
114
115   fn get_shared_inbox_or_inbox_url(&self) -> Url;
116
117   /// Outbox URL is not generally used by Lemmy, so it can be generated on the fly (but only for
118   /// local actors).
119   fn get_outbox_url(&self) -> Result<Url, LemmyError> {
120     /* TODO
121     if !self.is_local() {
122       return Err(anyhow!("get_outbox_url() called for remote actor").into());
123     }
124     */
125     Ok(Url::parse(&format!("{}/outbox", &self.actor_id()))?)
126   }
127
128   fn get_public_key(&self) -> Result<PublicKey, LemmyError> {
129     Ok(PublicKey {
130       id: format!("{}#main-key", self.actor_id()),
131       owner: self.actor_id(),
132       public_key_pem: self.public_key().context(location_info!())?,
133     })
134   }
135 }
136
137 #[async_trait::async_trait(?Send)]
138 pub trait CommunityType {
139   fn followers_url(&self) -> Url;
140   async fn get_follower_inboxes(&self, pool: &DbPool) -> Result<Vec<Url>, LemmyError>;
141 }
142
143 pub enum EndpointType {
144   Community,
145   Person,
146   Post,
147   Comment,
148   PrivateMessage,
149 }
150
151 /// Generates an apub endpoint for a given domain, IE xyz.tld
152 fn generate_apub_endpoint_for_domain(
153   endpoint_type: EndpointType,
154   name: &str,
155   domain: &str,
156 ) -> Result<DbUrl, ParseError> {
157   let point = match endpoint_type {
158     EndpointType::Community => "c",
159     EndpointType::Person => "u",
160     EndpointType::Post => "post",
161     EndpointType::Comment => "comment",
162     EndpointType::PrivateMessage => "private_message",
163   };
164
165   Ok(Url::parse(&format!("{}/{}/{}", domain, point, name))?.into())
166 }
167
168 /// Generates the ActivityPub ID for a given object type and ID.
169 pub fn generate_apub_endpoint(
170   endpoint_type: EndpointType,
171   name: &str,
172 ) -> Result<DbUrl, ParseError> {
173   generate_apub_endpoint_for_domain(
174     endpoint_type,
175     name,
176     &Settings::get().get_protocol_and_hostname(),
177   )
178 }
179
180 pub fn generate_followers_url(actor_id: &DbUrl) -> Result<DbUrl, ParseError> {
181   Ok(Url::parse(&format!("{}/followers", actor_id))?.into())
182 }
183
184 pub fn generate_inbox_url(actor_id: &DbUrl) -> Result<DbUrl, ParseError> {
185   Ok(Url::parse(&format!("{}/inbox", actor_id))?.into())
186 }
187
188 pub fn generate_shared_inbox_url(actor_id: &DbUrl) -> Result<DbUrl, LemmyError> {
189   let actor_id: Url = actor_id.clone().into();
190   let url = format!(
191     "{}://{}{}/inbox",
192     &actor_id.scheme(),
193     &actor_id.host_str().context(location_info!())?,
194     if let Some(port) = actor_id.port() {
195       format!(":{}", port)
196     } else {
197       "".to_string()
198     },
199   );
200   Ok(Url::parse(&url)?.into())
201 }
202
203 fn generate_moderators_url(community_id: &DbUrl) -> Result<DbUrl, LemmyError> {
204   Ok(Url::parse(&format!("{}/moderators", community_id))?.into())
205 }
206
207 /// Takes in a shortname of the type dessalines@xyz.tld or dessalines (assumed to be local), and outputs the actor id.
208 /// Used in the API for communities and users.
209 pub fn build_actor_id_from_shortname(
210   endpoint_type: EndpointType,
211   short_name: &str,
212 ) -> Result<DbUrl, ParseError> {
213   let split = short_name.split('@').collect::<Vec<&str>>();
214
215   let name = split[0];
216
217   // If there's no @, its local
218   let domain = if split.len() == 1 {
219     Settings::get().get_protocol_and_hostname()
220   } else {
221     format!("{}://{}", Settings::get().get_protocol_string(), split[1])
222   };
223
224   generate_apub_endpoint_for_domain(endpoint_type, name, &domain)
225 }
226
227 /// Store a sent or received activity in the database, for logging purposes. These records are not
228 /// persistent.
229 async fn insert_activity<T>(
230   ap_id: &Url,
231   activity: T,
232   local: bool,
233   sensitive: bool,
234   pool: &DbPool,
235 ) -> Result<(), LemmyError>
236 where
237   T: Serialize + std::fmt::Debug + Send + 'static,
238 {
239   let ap_id = ap_id.to_owned().into();
240   blocking(pool, move |conn| {
241     Activity::insert(conn, ap_id, &activity, local, sensitive)
242   })
243   .await??;
244   Ok(())
245 }
246
247 pub enum PostOrComment {
248   Comment(Box<Comment>),
249   Post(Box<Post>),
250 }
251
252 impl PostOrComment {
253   pub(crate) fn ap_id(&self) -> Url {
254     match self {
255       PostOrComment::Post(p) => p.ap_id.clone(),
256       PostOrComment::Comment(c) => c.ap_id.clone(),
257     }
258     .into()
259   }
260 }
261
262 /// Tries to find a post or comment in the local database, without any network requests.
263 /// This is used to handle deletions and removals, because in case we dont have the object, we can
264 /// simply ignore the activity.
265 pub(crate) async fn find_post_or_comment_by_id(
266   context: &LemmyContext,
267   apub_id: Url,
268 ) -> Result<PostOrComment, LemmyError> {
269   let ap_id = apub_id.clone();
270   let post = blocking(context.pool(), move |conn| {
271     Post::read_from_apub_id(conn, &ap_id.into())
272   })
273   .await?;
274   if let Ok(p) = post {
275     return Ok(PostOrComment::Post(Box::new(p)));
276   }
277
278   let ap_id = apub_id.clone();
279   let comment = blocking(context.pool(), move |conn| {
280     Comment::read_from_apub_id(conn, &ap_id.into())
281   })
282   .await?;
283   if let Ok(c) = comment {
284     return Ok(PostOrComment::Comment(Box::new(c)));
285   }
286
287   Err(NotFound.into())
288 }
289
290 #[derive(Debug)]
291 enum Object {
292   Comment(Box<Comment>),
293   Post(Box<Post>),
294   Community(Box<Community>),
295   Person(Box<DbPerson>),
296   PrivateMessage(Box<PrivateMessage>),
297 }
298
299 async fn find_object_by_id(context: &LemmyContext, apub_id: Url) -> Result<Object, LemmyError> {
300   let ap_id = apub_id.clone();
301   if let Ok(pc) = find_post_or_comment_by_id(context, ap_id.to_owned()).await {
302     return Ok(match pc {
303       PostOrComment::Post(p) => Object::Post(Box::new(*p)),
304       PostOrComment::Comment(c) => Object::Comment(Box::new(*c)),
305     });
306   }
307
308   let ap_id = apub_id.clone();
309   let person = blocking(context.pool(), move |conn| {
310     DbPerson::read_from_apub_id(conn, &ap_id.into())
311   })
312   .await?;
313   if let Ok(u) = person {
314     return Ok(Object::Person(Box::new(u)));
315   }
316
317   let ap_id = apub_id.clone();
318   let community = blocking(context.pool(), move |conn| {
319     Community::read_from_apub_id(conn, &ap_id.into())
320   })
321   .await?;
322   if let Ok(c) = community {
323     return Ok(Object::Community(Box::new(c)));
324   }
325
326   let private_message = blocking(context.pool(), move |conn| {
327     PrivateMessage::read_from_apub_id(conn, &apub_id.into())
328   })
329   .await?;
330   if let Ok(pm) = private_message {
331     return Ok(Object::PrivateMessage(Box::new(pm)));
332   }
333
334   Err(NotFound.into())
335 }
336
337 async fn check_community_or_site_ban(
338   person: &Person,
339   community_id: CommunityId,
340   pool: &DbPool,
341 ) -> Result<(), LemmyError> {
342   if person.banned {
343     return Err(anyhow!("Person is banned from site").into());
344   }
345   let person_id = person.id;
346   let is_banned =
347     move |conn: &'_ _| CommunityPersonBanView::get(conn, person_id, community_id).is_ok();
348   if blocking(pool, is_banned).await? {
349     return Err(anyhow!("Person is banned from community").into());
350   }
351
352   Ok(())
353 }