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