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