]> Untitled Git - lemmy.git/blob - crates/apub/src/lib.rs
Add option to disable strict allowlist (fixes #1486) (#1581)
[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 objects;
9
10 use crate::{
11   extensions::{
12     group_extension::GroupExtension,
13     page_extension::PageExtension,
14     person_extension::PersonExtension,
15     signatures::{PublicKey, PublicKeyExtension},
16   },
17   fetcher::community::get_or_fetch_and_upsert_community,
18 };
19 use activitystreams::{
20   activity::Follow,
21   actor,
22   base::AnyBase,
23   object::{ApObject, AsObject, Note, ObjectExt, Page},
24 };
25 use activitystreams_ext::{Ext1, Ext2};
26 use anyhow::{anyhow, Context};
27 use diesel::NotFound;
28 use lemmy_api_common::blocking;
29 use lemmy_db_queries::{source::activity::Activity_, ApubObject, DbPool};
30 use lemmy_db_schema::{
31   source::{
32     activity::Activity,
33     comment::Comment,
34     community::Community,
35     person::{Person as DbPerson, Person},
36     post::Post,
37     private_message::PrivateMessage,
38   },
39   CommunityId,
40   DbUrl,
41 };
42 use lemmy_db_views_actor::community_person_ban_view::CommunityPersonBanView;
43 use lemmy_utils::{location_info, settings::structs::Settings, LemmyError};
44 use lemmy_websocket::LemmyContext;
45 use serde::Serialize;
46 use std::net::IpAddr;
47 use url::{ParseError, Url};
48
49 /// Activitystreams type for community
50 pub type GroupExt =
51   Ext2<actor::ApActor<ApObject<actor::Group>>, GroupExtension, PublicKeyExtension>;
52 /// Activitystreams type for person
53 type PersonExt = Ext2<actor::ApActor<ApObject<actor::Person>>, PersonExtension, PublicKeyExtension>;
54 /// Activitystreams type for post
55 pub type PageExt = Ext1<ApObject<Page>, PageExtension>;
56 pub type NoteExt = ApObject<Note>;
57
58 pub static APUB_JSON_CONTENT_TYPE: &str = "application/activity+json";
59
60 /// Checks if the ID is allowed for sending or receiving.
61 ///
62 /// In particular, it checks for:
63 /// - federation being enabled (if its disabled, only local URLs are allowed)
64 /// - the correct scheme (either http or https)
65 /// - URL being in the allowlist (if it is active)
66 /// - URL not being in the blocklist (if it is active)
67 ///
68 pub fn check_is_apub_id_valid(apub_id: &Url, use_strict_allowlist: bool) -> Result<(), LemmyError> {
69   let settings = Settings::get();
70   let domain = apub_id.domain().context(location_info!())?.to_string();
71   let local_instance = settings.get_hostname_without_port()?;
72
73   if !settings.federation().enabled {
74     return if domain == local_instance {
75       Ok(())
76     } else {
77       Err(
78         anyhow!(
79           "Trying to connect with {}, but federation is disabled",
80           domain
81         )
82         .into(),
83       )
84     };
85   }
86
87   let host = apub_id.host_str().context(location_info!())?;
88   let host_as_ip = host.parse::<IpAddr>();
89   if host == "localhost" || host_as_ip.is_ok() {
90     return Err(anyhow!("invalid hostname {}: {}", host, apub_id).into());
91   }
92
93   if apub_id.scheme() != Settings::get().get_protocol_string() {
94     return Err(anyhow!("invalid apub id scheme {}: {}", apub_id.scheme(), apub_id).into());
95   }
96
97   // TODO: might be good to put the part above in one method, and below in another
98   //       (which only gets called in apub::objects)
99   //        -> no that doesnt make sense, we still need the code below for blocklist and strict allowlist
100   if let Some(blocked) = Settings::get().get_blocked_instances() {
101     if blocked.contains(&domain) {
102       return Err(anyhow!("{} is in federation blocklist", domain).into());
103     }
104   }
105
106   if let Some(mut allowed) = Settings::get().get_allowed_instances() {
107     // Only check allowlist if this is a community, or strict allowlist is enabled.
108     let strict_allowlist = Settings::get()
109       .federation()
110       .strict_allowlist
111       .unwrap_or(true);
112     if use_strict_allowlist || strict_allowlist {
113       // need to allow this explicitly because apub receive might contain objects from our local
114       // instance.
115       allowed.push(local_instance);
116
117       if !allowed.contains(&domain) {
118         return Err(anyhow!("{} not in federation allowlist", domain).into());
119       }
120     }
121   }
122
123   Ok(())
124 }
125
126 /// Common functions for ActivityPub objects, which are implemented by most (but not all) objects
127 /// and actors in Lemmy.
128 #[async_trait::async_trait(?Send)]
129 pub trait ApubObjectType {
130   async fn send_create(&self, creator: &DbPerson, context: &LemmyContext)
131     -> Result<(), LemmyError>;
132   async fn send_update(&self, creator: &DbPerson, context: &LemmyContext)
133     -> Result<(), LemmyError>;
134   async fn send_delete(&self, creator: &DbPerson, context: &LemmyContext)
135     -> Result<(), LemmyError>;
136   async fn send_undo_delete(
137     &self,
138     creator: &DbPerson,
139     context: &LemmyContext,
140   ) -> Result<(), LemmyError>;
141   async fn send_remove(&self, mod_: &DbPerson, context: &LemmyContext) -> Result<(), LemmyError>;
142   async fn send_undo_remove(
143     &self,
144     mod_: &DbPerson,
145     context: &LemmyContext,
146   ) -> Result<(), LemmyError>;
147 }
148
149 #[async_trait::async_trait(?Send)]
150 pub trait ApubLikeableType {
151   async fn send_like(&self, creator: &DbPerson, context: &LemmyContext) -> Result<(), LemmyError>;
152   async fn send_dislike(
153     &self,
154     creator: &DbPerson,
155     context: &LemmyContext,
156   ) -> Result<(), LemmyError>;
157   async fn send_undo_like(
158     &self,
159     creator: &DbPerson,
160     context: &LemmyContext,
161   ) -> Result<(), LemmyError>;
162 }
163
164 /// Common methods provided by ActivityPub actors (community and person). Not all methods are
165 /// implemented by all actors.
166 #[async_trait::async_trait(?Send)]
167 pub trait ActorType {
168   fn is_local(&self) -> bool;
169   fn actor_id(&self) -> Url;
170
171   // TODO: every actor should have a public key, so this shouldnt be an option (needs to be fixed in db)
172   fn public_key(&self) -> Option<String>;
173   fn private_key(&self) -> Option<String>;
174
175   fn get_shared_inbox_or_inbox_url(&self) -> Url;
176
177   /// Outbox URL is not generally used by Lemmy, so it can be generated on the fly (but only for
178   /// local actors).
179   fn get_outbox_url(&self) -> Result<Url, LemmyError> {
180     /* TODO
181     if !self.is_local() {
182       return Err(anyhow!("get_outbox_url() called for remote actor").into());
183     }
184     */
185     Ok(Url::parse(&format!("{}/outbox", &self.actor_id()))?)
186   }
187
188   fn get_public_key_ext(&self) -> Result<PublicKeyExtension, LemmyError> {
189     Ok(
190       PublicKey {
191         id: format!("{}#main-key", self.actor_id()),
192         owner: self.actor_id(),
193         public_key_pem: self.public_key().context(location_info!())?,
194       }
195       .to_ext(),
196     )
197   }
198 }
199
200 #[async_trait::async_trait(?Send)]
201 pub trait CommunityType {
202   fn followers_url(&self) -> Url;
203   async fn get_follower_inboxes(&self, pool: &DbPool) -> Result<Vec<Url>, LemmyError>;
204   async fn send_accept_follow(
205     &self,
206     follow: Follow,
207     context: &LemmyContext,
208   ) -> Result<(), LemmyError>;
209
210   async fn send_update(&self, mod_: Person, context: &LemmyContext) -> Result<(), LemmyError>;
211   async fn send_delete(&self, mod_: Person, context: &LemmyContext) -> Result<(), LemmyError>;
212   async fn send_undo_delete(&self, mod_: Person, context: &LemmyContext) -> Result<(), LemmyError>;
213
214   async fn send_remove(&self, context: &LemmyContext) -> Result<(), LemmyError>;
215   async fn send_undo_remove(&self, context: &LemmyContext) -> Result<(), LemmyError>;
216
217   async fn send_announce(
218     &self,
219     activity: AnyBase,
220     object: Option<Url>,
221     context: &LemmyContext,
222   ) -> Result<(), LemmyError>;
223
224   async fn send_add_mod(
225     &self,
226     actor: &Person,
227     added_mod: Person,
228     context: &LemmyContext,
229   ) -> Result<(), LemmyError>;
230   async fn send_remove_mod(
231     &self,
232     actor: &Person,
233     removed_mod: Person,
234     context: &LemmyContext,
235   ) -> Result<(), LemmyError>;
236
237   async fn send_block_user(
238     &self,
239     actor: &Person,
240     blocked_user: Person,
241     context: &LemmyContext,
242   ) -> Result<(), LemmyError>;
243   async fn send_undo_block_user(
244     &self,
245     actor: &Person,
246     blocked_user: Person,
247     context: &LemmyContext,
248   ) -> Result<(), LemmyError>;
249 }
250
251 #[async_trait::async_trait(?Send)]
252 pub trait UserType {
253   async fn send_follow(
254     &self,
255     follow_actor_id: &Url,
256     context: &LemmyContext,
257   ) -> Result<(), LemmyError>;
258   async fn send_unfollow(
259     &self,
260     follow_actor_id: &Url,
261     context: &LemmyContext,
262   ) -> Result<(), LemmyError>;
263 }
264
265 pub enum EndpointType {
266   Community,
267   Person,
268   Post,
269   Comment,
270   PrivateMessage,
271 }
272
273 /// Generates the ActivityPub ID for a given object type and ID.
274 pub fn generate_apub_endpoint(
275   endpoint_type: EndpointType,
276   name: &str,
277 ) -> Result<DbUrl, ParseError> {
278   let point = match endpoint_type {
279     EndpointType::Community => "c",
280     EndpointType::Person => "u",
281     EndpointType::Post => "post",
282     EndpointType::Comment => "comment",
283     EndpointType::PrivateMessage => "private_message",
284   };
285
286   Ok(
287     Url::parse(&format!(
288       "{}/{}/{}",
289       Settings::get().get_protocol_and_hostname(),
290       point,
291       name
292     ))?
293     .into(),
294   )
295 }
296
297 pub fn generate_followers_url(actor_id: &DbUrl) -> Result<DbUrl, ParseError> {
298   Ok(Url::parse(&format!("{}/followers", actor_id))?.into())
299 }
300
301 pub fn generate_inbox_url(actor_id: &DbUrl) -> Result<DbUrl, ParseError> {
302   Ok(Url::parse(&format!("{}/inbox", actor_id))?.into())
303 }
304
305 pub fn generate_shared_inbox_url(actor_id: &DbUrl) -> Result<DbUrl, LemmyError> {
306   let actor_id = actor_id.clone().into_inner();
307   let url = format!(
308     "{}://{}{}/inbox",
309     &actor_id.scheme(),
310     &actor_id.host_str().context(location_info!())?,
311     if let Some(port) = actor_id.port() {
312       format!(":{}", port)
313     } else {
314       "".to_string()
315     },
316   );
317   Ok(Url::parse(&url)?.into())
318 }
319
320 pub fn generate_moderators_url(community_id: &DbUrl) -> Result<DbUrl, LemmyError> {
321   Ok(Url::parse(&format!("{}/moderators", community_id))?.into())
322 }
323
324 /// Store a sent or received activity in the database, for logging purposes. These records are not
325 /// persistent.
326 pub async fn insert_activity<T>(
327   ap_id: &Url,
328   activity: T,
329   local: bool,
330   sensitive: bool,
331   pool: &DbPool,
332 ) -> Result<(), LemmyError>
333 where
334   T: Serialize + std::fmt::Debug + Send + 'static,
335 {
336   let ap_id = ap_id.to_owned().into();
337   blocking(pool, move |conn| {
338     Activity::insert(conn, ap_id, &activity, local, sensitive)
339   })
340   .await??;
341   Ok(())
342 }
343
344 pub enum PostOrComment {
345   Comment(Box<Comment>),
346   Post(Box<Post>),
347 }
348
349 /// Tries to find a post or comment in the local database, without any network requests.
350 /// This is used to handle deletions and removals, because in case we dont have the object, we can
351 /// simply ignore the activity.
352 pub async fn find_post_or_comment_by_id(
353   context: &LemmyContext,
354   apub_id: Url,
355 ) -> Result<PostOrComment, LemmyError> {
356   let ap_id = apub_id.clone();
357   let post = blocking(context.pool(), move |conn| {
358     Post::read_from_apub_id(conn, &ap_id.into())
359   })
360   .await?;
361   if let Ok(p) = post {
362     return Ok(PostOrComment::Post(Box::new(p)));
363   }
364
365   let ap_id = apub_id.clone();
366   let comment = blocking(context.pool(), move |conn| {
367     Comment::read_from_apub_id(conn, &ap_id.into())
368   })
369   .await?;
370   if let Ok(c) = comment {
371     return Ok(PostOrComment::Comment(Box::new(c)));
372   }
373
374   Err(NotFound.into())
375 }
376
377 #[derive(Debug)]
378 pub enum Object {
379   Comment(Box<Comment>),
380   Post(Box<Post>),
381   Community(Box<Community>),
382   Person(Box<DbPerson>),
383   PrivateMessage(Box<PrivateMessage>),
384 }
385
386 pub async fn find_object_by_id(context: &LemmyContext, apub_id: Url) -> Result<Object, LemmyError> {
387   let ap_id = apub_id.clone();
388   if let Ok(pc) = find_post_or_comment_by_id(context, ap_id.to_owned()).await {
389     return Ok(match pc {
390       PostOrComment::Post(p) => Object::Post(Box::new(*p)),
391       PostOrComment::Comment(c) => Object::Comment(Box::new(*c)),
392     });
393   }
394
395   let ap_id = apub_id.clone();
396   let person = blocking(context.pool(), move |conn| {
397     DbPerson::read_from_apub_id(conn, &ap_id.into())
398   })
399   .await?;
400   if let Ok(u) = person {
401     return Ok(Object::Person(Box::new(u)));
402   }
403
404   let ap_id = apub_id.clone();
405   let community = blocking(context.pool(), move |conn| {
406     Community::read_from_apub_id(conn, &ap_id.into())
407   })
408   .await?;
409   if let Ok(c) = community {
410     return Ok(Object::Community(Box::new(c)));
411   }
412
413   let private_message = blocking(context.pool(), move |conn| {
414     PrivateMessage::read_from_apub_id(conn, &apub_id.into())
415   })
416   .await?;
417   if let Ok(pm) = private_message {
418     return Ok(Object::PrivateMessage(Box::new(pm)));
419   }
420
421   Err(NotFound.into())
422 }
423
424 pub async fn check_community_or_site_ban(
425   person: &Person,
426   community_id: CommunityId,
427   pool: &DbPool,
428 ) -> Result<(), LemmyError> {
429   if person.banned {
430     return Err(anyhow!("Person is banned from site").into());
431   }
432   let person_id = person.id;
433   let is_banned =
434     move |conn: &'_ _| CommunityPersonBanView::get(conn, person_id, community_id).is_ok();
435   if blocking(pool, is_banned).await? {
436     return Err(anyhow!("Person is banned from community").into());
437   }
438
439   Ok(())
440 }
441
442 pub fn get_activity_to_and_cc<T, Kind>(activity: &T) -> Vec<Url>
443 where
444   T: AsObject<Kind>,
445 {
446   let mut to_and_cc = vec![];
447   if let Some(to) = activity.to() {
448     let to = to.to_owned().unwrap_to_vec();
449     let mut to = to
450       .iter()
451       .map(|t| t.as_xsd_any_uri())
452       .flatten()
453       .map(|t| t.to_owned())
454       .collect();
455     to_and_cc.append(&mut to);
456   }
457   if let Some(cc) = activity.cc() {
458     let cc = cc.to_owned().unwrap_to_vec();
459     let mut cc = cc
460       .iter()
461       .map(|c| c.as_xsd_any_uri())
462       .flatten()
463       .map(|c| c.to_owned())
464       .collect();
465     to_and_cc.append(&mut cc);
466   }
467   to_and_cc
468 }
469
470 pub async fn get_community_from_to_or_cc<T, Kind>(
471   activity: &T,
472   context: &LemmyContext,
473   request_counter: &mut i32,
474 ) -> Result<Community, LemmyError>
475 where
476   T: AsObject<Kind>,
477 {
478   for cid in get_activity_to_and_cc(activity) {
479     let community = get_or_fetch_and_upsert_community(&cid, context, request_counter).await;
480     if community.is_ok() {
481       return community;
482     }
483   }
484   Err(NotFound.into())
485 }