]> Untitled Git - lemmy.git/blob - crates/apub/src/lib.rs
Rewrite collections to use new fetcher (#1861)
[lemmy.git] / crates / apub / src / lib.rs
1 pub mod activities;
2 pub(crate) mod collections;
3 mod context;
4 pub mod fetcher;
5 pub mod http;
6 pub mod migrations;
7 pub mod objects;
8
9 #[macro_use]
10 extern crate lazy_static;
11
12 use crate::fetcher::post_or_comment::PostOrComment;
13 use anyhow::{anyhow, Context};
14 use lemmy_api_common::blocking;
15 use lemmy_apub_lib::{activity_queue::send_activity, traits::ActorType};
16 use lemmy_db_schema::{
17   newtypes::{CommunityId, DbUrl},
18   source::{activity::Activity, person::Person},
19   DbPool,
20 };
21 use lemmy_db_views_actor::community_person_ban_view::CommunityPersonBanView;
22 use lemmy_utils::{location_info, settings::structs::Settings, LemmyError};
23 use lemmy_websocket::LemmyContext;
24 use log::info;
25 use serde::Serialize;
26 use std::net::IpAddr;
27 use url::{ParseError, Url};
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 #[async_trait::async_trait(?Send)]
96 pub trait CommunityType {
97   fn followers_url(&self) -> Url;
98   async fn get_follower_inboxes(
99     &self,
100     pool: &DbPool,
101     settings: &Settings,
102   ) -> Result<Vec<Url>, LemmyError>;
103 }
104
105 pub enum EndpointType {
106   Community,
107   Person,
108   Post,
109   Comment,
110   PrivateMessage,
111 }
112
113 /// Generates an apub endpoint for a given domain, IE xyz.tld
114 fn generate_apub_endpoint_for_domain(
115   endpoint_type: EndpointType,
116   name: &str,
117   domain: &str,
118 ) -> Result<DbUrl, ParseError> {
119   let point = match endpoint_type {
120     EndpointType::Community => "c",
121     EndpointType::Person => "u",
122     EndpointType::Post => "post",
123     EndpointType::Comment => "comment",
124     EndpointType::PrivateMessage => "private_message",
125   };
126
127   Ok(Url::parse(&format!("{}/{}/{}", domain, point, name))?.into())
128 }
129
130 /// Generates the ActivityPub ID for a given object type and ID.
131 pub fn generate_apub_endpoint(
132   endpoint_type: EndpointType,
133   name: &str,
134   protocol_and_hostname: &str,
135 ) -> Result<DbUrl, ParseError> {
136   generate_apub_endpoint_for_domain(endpoint_type, name, protocol_and_hostname)
137 }
138
139 pub fn generate_followers_url(actor_id: &DbUrl) -> Result<DbUrl, ParseError> {
140   Ok(Url::parse(&format!("{}/followers", actor_id))?.into())
141 }
142
143 pub fn generate_inbox_url(actor_id: &DbUrl) -> Result<DbUrl, ParseError> {
144   Ok(Url::parse(&format!("{}/inbox", actor_id))?.into())
145 }
146
147 pub fn generate_shared_inbox_url(actor_id: &DbUrl) -> Result<DbUrl, LemmyError> {
148   let actor_id: Url = actor_id.clone().into();
149   let url = format!(
150     "{}://{}{}/inbox",
151     &actor_id.scheme(),
152     &actor_id.host_str().context(location_info!())?,
153     if let Some(port) = actor_id.port() {
154       format!(":{}", port)
155     } else {
156       "".to_string()
157     },
158   );
159   Ok(Url::parse(&url)?.into())
160 }
161
162 pub fn generate_outbox_url(actor_id: &DbUrl) -> Result<DbUrl, ParseError> {
163   Ok(Url::parse(&format!("{}/outbox", actor_id))?.into())
164 }
165
166 fn generate_moderators_url(community_id: &DbUrl) -> Result<DbUrl, LemmyError> {
167   Ok(Url::parse(&format!("{}/moderators", community_id))?.into())
168 }
169
170 /// Takes in a shortname of the type dessalines@xyz.tld or dessalines (assumed to be local), and outputs the actor id.
171 /// Used in the API for communities and users.
172 pub fn build_actor_id_from_shortname(
173   endpoint_type: EndpointType,
174   short_name: &str,
175   settings: &Settings,
176 ) -> Result<DbUrl, ParseError> {
177   let split = short_name.split('@').collect::<Vec<&str>>();
178
179   let name = split[0];
180
181   // If there's no @, its local
182   let domain = if split.len() == 1 {
183     settings.get_protocol_and_hostname()
184   } else {
185     format!("{}://{}", settings.get_protocol_string(), split[1])
186   };
187
188   generate_apub_endpoint_for_domain(endpoint_type, name, &domain)
189 }
190
191 /// Store a sent or received activity in the database, for logging purposes. These records are not
192 /// persistent.
193 async fn insert_activity<T>(
194   ap_id: &Url,
195   activity: T,
196   local: bool,
197   sensitive: bool,
198   pool: &DbPool,
199 ) -> Result<(), LemmyError>
200 where
201   T: Serialize + std::fmt::Debug + Send + 'static,
202 {
203   let ap_id = ap_id.to_owned().into();
204   blocking(pool, move |conn| {
205     Activity::insert(conn, ap_id, &activity, local, sensitive)
206   })
207   .await??;
208   Ok(())
209 }
210
211 async fn check_community_or_site_ban(
212   person: &Person,
213   community_id: CommunityId,
214   pool: &DbPool,
215 ) -> Result<(), LemmyError> {
216   if person.banned {
217     return Err(anyhow!("Person is banned from site").into());
218   }
219   let person_id = person.id;
220   let is_banned =
221     move |conn: &'_ _| CommunityPersonBanView::get(conn, person_id, community_id).is_ok();
222   if blocking(pool, is_banned).await? {
223     return Err(anyhow!("Person is banned from community").into());
224   }
225
226   Ok(())
227 }
228
229 pub(crate) async fn send_lemmy_activity<T: Serialize>(
230   context: &LemmyContext,
231   activity: &T,
232   activity_id: &Url,
233   actor: &dyn ActorType,
234   inboxes: Vec<Url>,
235   sensitive: bool,
236 ) -> Result<(), LemmyError> {
237   if !context.settings().federation.enabled || inboxes.is_empty() {
238     return Ok(());
239   }
240
241   info!("Sending activity {}", activity_id.to_string());
242
243   // Don't send anything to ourselves
244   // TODO: this should be a debug assert
245   let hostname = context.settings().get_hostname_without_port()?;
246   let inboxes: Vec<&Url> = inboxes
247     .iter()
248     .filter(|i| i.domain().expect("valid inbox url") != hostname)
249     .collect();
250
251   let serialised_activity = serde_json::to_string(&activity)?;
252
253   insert_activity(
254     activity_id,
255     serialised_activity.clone(),
256     true,
257     sensitive,
258     context.pool(),
259   )
260   .await?;
261
262   send_activity(
263     serialised_activity,
264     actor,
265     inboxes,
266     context.client(),
267     context.activity_queue(),
268   )
269   .await
270 }