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