]> Untitled Git - lemmy.git/blob - lemmy_apub/src/lib.rs
e7410ee253aa628a72c411923378c335cacda864
[lemmy.git] / lemmy_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
12 use crate::extensions::{
13   group_extensions::GroupExtension,
14   page_extension::PageExtension,
15   signatures::{PublicKey, PublicKeyExtension},
16 };
17 use activitystreams::{
18   activity::Follow,
19   actor::{ApActor, Group, Person},
20   base::AnyBase,
21   object::{Page, Tombstone},
22 };
23 use activitystreams_ext::{Ext1, Ext2};
24 use anyhow::{anyhow, Context};
25 use lemmy_db::{activity::Activity, user::User_, DbPool};
26 use lemmy_structs::blocking;
27 use lemmy_utils::{location_info, settings::Settings, LemmyError};
28 use lemmy_websocket::LemmyContext;
29 use serde::Serialize;
30 use std::net::IpAddr;
31 use url::{ParseError, Url};
32
33 /// Activitystreams type for community
34 type GroupExt = Ext2<ApActor<Group>, GroupExtension, PublicKeyExtension>;
35 /// Activitystreams type for user
36 type PersonExt = Ext1<ApActor<Person>, PublicKeyExtension>;
37 /// Activitystreams type for post
38 type PageExt = Ext1<Page, PageExtension>;
39
40 pub static APUB_JSON_CONTENT_TYPE: &str = "application/activity+json";
41
42 /// Checks if the ID is allowed for sending or receiving.
43 ///
44 /// In particular, it checks for:
45 /// - federation being enabled (if its disabled, only local URLs are allowed)
46 /// - the correct scheme (either http or https)
47 /// - URL being in the allowlist (if it is active)
48 /// - URL not being in the blocklist (if it is active)
49 ///
50 /// Note that only one of allowlist and blacklist can be enabled, not both.
51 fn check_is_apub_id_valid(apub_id: &Url) -> Result<(), LemmyError> {
52   let settings = Settings::get();
53   let domain = apub_id.domain().context(location_info!())?.to_string();
54   let local_instance = settings
55     .hostname
56     .split(':')
57     .collect::<Vec<&str>>()
58     .first()
59     .context(location_info!())?
60     .to_string();
61
62   if !settings.federation.enabled {
63     return if domain == local_instance {
64       Ok(())
65     } else {
66       Err(
67         anyhow!(
68           "Trying to connect with {}, but federation is disabled",
69           domain
70         )
71         .into(),
72       )
73     };
74   }
75
76   let host = apub_id.host_str().context(location_info!())?;
77   let host_as_ip = host.parse::<IpAddr>();
78   if host == "localhost" || host_as_ip.is_ok() {
79     return Err(anyhow!("invalid hostname: {:?}", host).into());
80   }
81
82   if apub_id.scheme() != Settings::get().get_protocol_string() {
83     return Err(anyhow!("invalid apub id scheme: {:?}", apub_id.scheme()).into());
84   }
85
86   let mut allowed_instances = Settings::get().get_allowed_instances();
87   let blocked_instances = Settings::get().get_blocked_instances();
88   if allowed_instances.is_empty() && blocked_instances.is_empty() {
89     Ok(())
90   } else if !allowed_instances.is_empty() {
91     // need to allow this explicitly because apub receive might contain objects from our local
92     // instance. split is needed to remove the port in our federation test setup.
93     allowed_instances.push(local_instance);
94
95     if allowed_instances.contains(&domain) {
96       Ok(())
97     } else {
98       Err(anyhow!("{} not in federation allowlist", domain).into())
99     }
100   } else if !blocked_instances.is_empty() {
101     if blocked_instances.contains(&domain) {
102       Err(anyhow!("{} is in federation blocklist", domain).into())
103     } else {
104       Ok(())
105     }
106   } else {
107     panic!("Invalid config, both allowed_instances and blocked_instances are specified");
108   }
109 }
110
111 /// Trait for converting an object or actor into the respective ActivityPub type.
112 #[async_trait::async_trait(?Send)]
113 pub trait ToApub {
114   type ApubType;
115   async fn to_apub(&self, pool: &DbPool) -> Result<Self::ApubType, LemmyError>;
116   fn to_tombstone(&self) -> Result<Tombstone, LemmyError>;
117 }
118
119 #[async_trait::async_trait(?Send)]
120 pub trait FromApub {
121   type ApubType;
122   /// Converts an object from ActivityPub type to Lemmy internal type.
123   ///
124   /// * `apub` The object to read from
125   /// * `context` LemmyContext which holds DB pool, HTTP client etc
126   /// * `expected_domain` If present, ensure that the domains of this and of the apub object ID are
127   ///                     identical
128   async fn from_apub(
129     apub: &Self::ApubType,
130     context: &LemmyContext,
131     expected_domain: Option<Url>,
132     request_counter: &mut i32,
133   ) -> Result<Self, LemmyError>
134   where
135     Self: Sized;
136 }
137
138 /// Common functions for ActivityPub objects, which are implemented by most (but not all) objects
139 /// and actors in Lemmy.
140 #[async_trait::async_trait(?Send)]
141 pub trait ApubObjectType {
142   async fn send_create(&self, creator: &User_, context: &LemmyContext) -> Result<(), LemmyError>;
143   async fn send_update(&self, creator: &User_, context: &LemmyContext) -> Result<(), LemmyError>;
144   async fn send_delete(&self, creator: &User_, context: &LemmyContext) -> Result<(), LemmyError>;
145   async fn send_undo_delete(
146     &self,
147     creator: &User_,
148     context: &LemmyContext,
149   ) -> Result<(), LemmyError>;
150   async fn send_remove(&self, mod_: &User_, context: &LemmyContext) -> Result<(), LemmyError>;
151   async fn send_undo_remove(&self, mod_: &User_, context: &LemmyContext) -> Result<(), LemmyError>;
152 }
153
154 #[async_trait::async_trait(?Send)]
155 pub trait ApubLikeableType {
156   async fn send_like(&self, creator: &User_, context: &LemmyContext) -> Result<(), LemmyError>;
157   async fn send_dislike(&self, creator: &User_, context: &LemmyContext) -> Result<(), LemmyError>;
158   async fn send_undo_like(&self, creator: &User_, context: &LemmyContext)
159     -> Result<(), LemmyError>;
160 }
161
162 /// Common methods provided by ActivityPub actors (community and user). Not all methods are
163 /// implemented by all actors.
164 #[async_trait::async_trait(?Send)]
165 pub trait ActorType {
166   fn actor_id_str(&self) -> String;
167
168   // TODO: every actor should have a public key, so this shouldnt be an option (needs to be fixed in db)
169   fn public_key(&self) -> Option<String>;
170   fn private_key(&self) -> Option<String>;
171
172   /// numeric id in the database, used for insert_activity
173   fn user_id(&self) -> i32;
174
175   async fn send_follow(
176     &self,
177     follow_actor_id: &Url,
178     context: &LemmyContext,
179   ) -> Result<(), LemmyError>;
180   async fn send_unfollow(
181     &self,
182     follow_actor_id: &Url,
183     context: &LemmyContext,
184   ) -> Result<(), LemmyError>;
185
186   async fn send_accept_follow(
187     &self,
188     follow: Follow,
189     context: &LemmyContext,
190   ) -> Result<(), LemmyError>;
191
192   async fn send_delete(&self, context: &LemmyContext) -> Result<(), LemmyError>;
193   async fn send_undo_delete(&self, context: &LemmyContext) -> Result<(), LemmyError>;
194
195   async fn send_remove(&self, context: &LemmyContext) -> Result<(), LemmyError>;
196   async fn send_undo_remove(&self, context: &LemmyContext) -> Result<(), LemmyError>;
197
198   async fn send_announce(
199     &self,
200     activity: AnyBase,
201     context: &LemmyContext,
202   ) -> Result<(), LemmyError>;
203
204   /// For a given community, returns the inboxes of all followers.
205   async fn get_follower_inboxes(&self, pool: &DbPool) -> Result<Vec<Url>, LemmyError>;
206
207   fn actor_id(&self) -> Result<Url, ParseError> {
208     Url::parse(&self.actor_id_str())
209   }
210
211   // TODO move these to the db rows
212   fn get_inbox_url(&self) -> Result<Url, ParseError> {
213     Url::parse(&format!("{}/inbox", &self.actor_id_str()))
214   }
215
216   fn get_shared_inbox_url(&self) -> Result<Url, LemmyError> {
217     let actor_id = self.actor_id()?;
218     let url = format!(
219       "{}://{}{}/inbox",
220       &actor_id.scheme(),
221       &actor_id.host_str().context(location_info!())?,
222       if let Some(port) = actor_id.port() {
223         format!(":{}", port)
224       } else {
225         "".to_string()
226       },
227     );
228     Ok(Url::parse(&url)?)
229   }
230
231   fn get_outbox_url(&self) -> Result<Url, ParseError> {
232     Url::parse(&format!("{}/outbox", &self.actor_id_str()))
233   }
234
235   fn get_followers_url(&self) -> Result<Url, ParseError> {
236     Url::parse(&format!("{}/followers", &self.actor_id_str()))
237   }
238
239   fn get_public_key_ext(&self) -> Result<PublicKeyExtension, LemmyError> {
240     Ok(
241       PublicKey {
242         id: format!("{}#main-key", self.actor_id_str()),
243         owner: self.actor_id_str(),
244         public_key_pem: self.public_key().context(location_info!())?,
245       }
246       .to_ext(),
247     )
248   }
249 }
250
251 /// Store a sent or received activity in the database, for logging purposes. These records are not
252 /// persistent.
253 pub async fn insert_activity<T>(
254   ap_id: &Url,
255   user_id: i32,
256   activity: T,
257   local: bool,
258   pool: &DbPool,
259 ) -> Result<(), LemmyError>
260 where
261   T: Serialize + std::fmt::Debug + Send + 'static,
262 {
263   let ap_id = ap_id.to_string();
264   blocking(pool, move |conn| {
265     Activity::insert(conn, ap_id, user_id, &activity, local)
266   })
267   .await??;
268   Ok(())
269 }