]> Untitled Git - lemmy.git/blob - crates/apub/src/lib.rs
Moving settings and secrets to context.
[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   settings: &Settings,
41 ) -> Result<(), LemmyError> {
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_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.to_owned().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.to_owned().federation.allowed_instances {
79     // Only check allowlist if this is a community, or strict allowlist is enabled.
80     let strict_allowlist = settings.to_owned().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(
132     &self,
133     pool: &DbPool,
134     settings: &Settings,
135   ) -> Result<Vec<Url>, LemmyError>;
136 }
137
138 pub enum EndpointType {
139   Community,
140   Person,
141   Post,
142   Comment,
143   PrivateMessage,
144 }
145
146 /// Generates an apub endpoint for a given domain, IE xyz.tld
147 fn generate_apub_endpoint_for_domain(
148   endpoint_type: EndpointType,
149   name: &str,
150   domain: &str,
151 ) -> Result<DbUrl, ParseError> {
152   let point = match endpoint_type {
153     EndpointType::Community => "c",
154     EndpointType::Person => "u",
155     EndpointType::Post => "post",
156     EndpointType::Comment => "comment",
157     EndpointType::PrivateMessage => "private_message",
158   };
159
160   Ok(Url::parse(&format!("{}/{}/{}", domain, point, name))?.into())
161 }
162
163 /// Generates the ActivityPub ID for a given object type and ID.
164 pub fn generate_apub_endpoint(
165   endpoint_type: EndpointType,
166   name: &str,
167   protocol_and_hostname: &str,
168 ) -> Result<DbUrl, ParseError> {
169   generate_apub_endpoint_for_domain(endpoint_type, name, protocol_and_hostname)
170 }
171
172 pub fn generate_followers_url(actor_id: &DbUrl) -> Result<DbUrl, ParseError> {
173   Ok(Url::parse(&format!("{}/followers", actor_id))?.into())
174 }
175
176 pub fn generate_inbox_url(actor_id: &DbUrl) -> Result<DbUrl, ParseError> {
177   Ok(Url::parse(&format!("{}/inbox", actor_id))?.into())
178 }
179
180 pub fn generate_shared_inbox_url(actor_id: &DbUrl) -> Result<DbUrl, LemmyError> {
181   let actor_id: Url = actor_id.clone().into();
182   let url = format!(
183     "{}://{}{}/inbox",
184     &actor_id.scheme(),
185     &actor_id.host_str().context(location_info!())?,
186     if let Some(port) = actor_id.port() {
187       format!(":{}", port)
188     } else {
189       "".to_string()
190     },
191   );
192   Ok(Url::parse(&url)?.into())
193 }
194
195 fn generate_moderators_url(community_id: &DbUrl) -> Result<DbUrl, LemmyError> {
196   Ok(Url::parse(&format!("{}/moderators", community_id))?.into())
197 }
198
199 /// Takes in a shortname of the type dessalines@xyz.tld or dessalines (assumed to be local), and outputs the actor id.
200 /// Used in the API for communities and users.
201 pub fn build_actor_id_from_shortname(
202   endpoint_type: EndpointType,
203   short_name: &str,
204   settings: &Settings,
205 ) -> Result<DbUrl, ParseError> {
206   let split = short_name.split('@').collect::<Vec<&str>>();
207
208   let name = split[0];
209
210   // If there's no @, its local
211   let domain = if split.len() == 1 {
212     settings.get_protocol_and_hostname()
213   } else {
214     format!("{}://{}", settings.get_protocol_string(), split[1])
215   };
216
217   generate_apub_endpoint_for_domain(endpoint_type, name, &domain)
218 }
219
220 /// Store a sent or received activity in the database, for logging purposes. These records are not
221 /// persistent.
222 async fn insert_activity<T>(
223   ap_id: &Url,
224   activity: T,
225   local: bool,
226   sensitive: bool,
227   pool: &DbPool,
228 ) -> Result<(), LemmyError>
229 where
230   T: Serialize + std::fmt::Debug + Send + 'static,
231 {
232   let ap_id = ap_id.to_owned().into();
233   blocking(pool, move |conn| {
234     Activity::insert(conn, ap_id, &activity, local, sensitive)
235   })
236   .await??;
237   Ok(())
238 }
239
240 async fn check_community_or_site_ban(
241   person: &Person,
242   community_id: CommunityId,
243   pool: &DbPool,
244 ) -> Result<(), LemmyError> {
245   if person.banned {
246     return Err(anyhow!("Person is banned from site").into());
247   }
248   let person_id = person.id;
249   let is_banned =
250     move |conn: &'_ _| CommunityPersonBanView::get(conn, person_id, community_id).is_ok();
251   if blocking(pool, is_banned).await? {
252     return Err(anyhow!("Person is banned from community").into());
253   }
254
255   Ok(())
256 }