]> Untitled Git - lemmy.git/blob - lemmy_apub/src/lib.rs
In activity table, remove `user_id` and add `sensitive` (#127)
[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   async fn send_follow(
173     &self,
174     follow_actor_id: &Url,
175     context: &LemmyContext,
176   ) -> Result<(), LemmyError>;
177   async fn send_unfollow(
178     &self,
179     follow_actor_id: &Url,
180     context: &LemmyContext,
181   ) -> Result<(), LemmyError>;
182
183   async fn send_accept_follow(
184     &self,
185     follow: Follow,
186     context: &LemmyContext,
187   ) -> Result<(), LemmyError>;
188
189   async fn send_delete(&self, context: &LemmyContext) -> Result<(), LemmyError>;
190   async fn send_undo_delete(&self, context: &LemmyContext) -> Result<(), LemmyError>;
191
192   async fn send_remove(&self, context: &LemmyContext) -> Result<(), LemmyError>;
193   async fn send_undo_remove(&self, context: &LemmyContext) -> Result<(), LemmyError>;
194
195   async fn send_announce(
196     &self,
197     activity: AnyBase,
198     context: &LemmyContext,
199   ) -> Result<(), LemmyError>;
200
201   /// For a given community, returns the inboxes of all followers.
202   async fn get_follower_inboxes(&self, pool: &DbPool) -> Result<Vec<Url>, LemmyError>;
203
204   fn actor_id(&self) -> Result<Url, ParseError> {
205     Url::parse(&self.actor_id_str())
206   }
207
208   // TODO move these to the db rows
209   fn get_inbox_url(&self) -> Result<Url, ParseError> {
210     Url::parse(&format!("{}/inbox", &self.actor_id_str()))
211   }
212
213   fn get_shared_inbox_url(&self) -> Result<Url, LemmyError> {
214     let actor_id = self.actor_id()?;
215     let url = format!(
216       "{}://{}{}/inbox",
217       &actor_id.scheme(),
218       &actor_id.host_str().context(location_info!())?,
219       if let Some(port) = actor_id.port() {
220         format!(":{}", port)
221       } else {
222         "".to_string()
223       },
224     );
225     Ok(Url::parse(&url)?)
226   }
227
228   fn get_outbox_url(&self) -> Result<Url, ParseError> {
229     Url::parse(&format!("{}/outbox", &self.actor_id_str()))
230   }
231
232   fn get_followers_url(&self) -> Result<Url, ParseError> {
233     Url::parse(&format!("{}/followers", &self.actor_id_str()))
234   }
235
236   fn get_public_key_ext(&self) -> Result<PublicKeyExtension, LemmyError> {
237     Ok(
238       PublicKey {
239         id: format!("{}#main-key", self.actor_id_str()),
240         owner: self.actor_id_str(),
241         public_key_pem: self.public_key().context(location_info!())?,
242       }
243       .to_ext(),
244     )
245   }
246 }
247
248 /// Store a sent or received activity in the database, for logging purposes. These records are not
249 /// persistent.
250 pub async fn insert_activity<T>(
251   ap_id: &Url,
252   activity: T,
253   local: bool,
254   sensitive: bool,
255   pool: &DbPool,
256 ) -> Result<(), LemmyError>
257 where
258   T: Serialize + std::fmt::Debug + Send + 'static,
259 {
260   let ap_id = ap_id.to_string();
261   blocking(pool, move |conn| {
262     Activity::insert(conn, ap_id, &activity, local, sensitive)
263   })
264   .await??;
265   Ok(())
266 }