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