]> Untitled Git - lemmy.git/blob - crates/apub/src/lib.rs
Rework error handling (fixes #1714) (#2135)
[lemmy.git] / crates / apub / src / lib.rs
1 use crate::fetcher::post_or_comment::PostOrComment;
2 use anyhow::{anyhow, Context};
3 use lemmy_api_common::blocking;
4 use lemmy_db_schema::{newtypes::DbUrl, source::activity::Activity, DbPool};
5 use lemmy_utils::{location_info, settings::structs::Settings, LemmyError};
6 use serde::{Deserialize, Deserializer};
7 use std::net::IpAddr;
8 use url::{ParseError, Url};
9
10 pub mod activities;
11 pub(crate) mod activity_lists;
12 pub(crate) mod collections;
13 mod context;
14 pub mod fetcher;
15 pub mod http;
16 pub(crate) mod mentions;
17 pub mod migrations;
18 pub mod objects;
19 pub mod protocol;
20
21 /// Checks if the ID is allowed for sending or receiving.
22 ///
23 /// In particular, it checks for:
24 /// - federation being enabled (if its disabled, only local URLs are allowed)
25 /// - the correct scheme (either http or https)
26 /// - URL being in the allowlist (if it is active)
27 /// - URL not being in the blocklist (if it is active)
28 ///
29 /// `use_strict_allowlist` should be true only when parsing a remote community, or when parsing a
30 /// post/comment in a local community.
31 #[tracing::instrument(skip(settings))]
32 pub(crate) fn check_is_apub_id_valid(
33   apub_id: &Url,
34   use_strict_allowlist: bool,
35   settings: &Settings,
36 ) -> Result<(), LemmyError> {
37   let domain = apub_id.domain().context(location_info!())?.to_string();
38   let local_instance = settings.get_hostname_without_port()?;
39
40   if !settings.federation.enabled {
41     return if domain == local_instance {
42       Ok(())
43     } else {
44       let err = anyhow!(
45         "Trying to connect with {}, but federation is disabled",
46         domain
47       );
48       Err(LemmyError::from_error_message(err, "federation_disabled"))
49     };
50   }
51
52   let host = apub_id.host_str().context(location_info!())?;
53   let host_as_ip = host.parse::<IpAddr>();
54   if host == "localhost" || host_as_ip.is_ok() {
55     let err = anyhow!("invalid hostname {}: {}", host, apub_id);
56     return Err(LemmyError::from_error_message(err, "invalid_hostname"));
57   }
58
59   if apub_id.scheme() != settings.get_protocol_string() {
60     let err = anyhow!("invalid apub id scheme {}: {}", apub_id.scheme(), apub_id);
61     return Err(LemmyError::from_error_message(err, "invalid_scheme"));
62   }
63
64   // TODO: might be good to put the part above in one method, and below in another
65   //       (which only gets called in apub::objects)
66   //        -> no that doesnt make sense, we still need the code below for blocklist and strict allowlist
67   if let Some(blocked) = settings.to_owned().federation.blocked_instances {
68     if blocked.contains(&domain) {
69       let err = anyhow!("{} is in federation blocklist", domain);
70       return Err(LemmyError::from_error_message(err, "federation_blocked"));
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         let err = anyhow!("{} not in federation allowlist", domain);
84         return Err(LemmyError::from_error_message(
85           err,
86           "federation_not_allowed",
87         ));
88       }
89     }
90   }
91
92   Ok(())
93 }
94
95 pub(crate) fn deserialize_one_or_many<'de, T, D>(deserializer: D) -> Result<Vec<T>, D::Error>
96 where
97   T: Deserialize<'de>,
98   D: Deserializer<'de>,
99 {
100   #[derive(Deserialize)]
101   #[serde(untagged)]
102   enum OneOrMany<T> {
103     One(T),
104     Many(Vec<T>),
105   }
106
107   let result: OneOrMany<T> = Deserialize::deserialize(deserializer)?;
108   Ok(match result {
109     OneOrMany::Many(list) => list,
110     OneOrMany::One(value) => vec![value],
111   })
112 }
113
114 pub(crate) fn deserialize_one<'de, T, D>(deserializer: D) -> Result<[T; 1], D::Error>
115 where
116   T: Deserialize<'de>,
117   D: Deserializer<'de>,
118 {
119   #[derive(Deserialize)]
120   #[serde(untagged)]
121   enum MaybeArray<T> {
122     Simple(T),
123     Array([T; 1]),
124   }
125
126   let result: MaybeArray<T> = Deserialize::deserialize(deserializer)?;
127   Ok(match result {
128     MaybeArray::Simple(value) => [value],
129     MaybeArray::Array(value) => value,
130   })
131 }
132
133 pub enum EndpointType {
134   Community,
135   Person,
136   Post,
137   Comment,
138   PrivateMessage,
139 }
140
141 /// Generates an apub endpoint for a given domain, IE xyz.tld
142 pub fn generate_local_apub_endpoint(
143   endpoint_type: EndpointType,
144   name: &str,
145   domain: &str,
146 ) -> Result<DbUrl, ParseError> {
147   let point = match endpoint_type {
148     EndpointType::Community => "c",
149     EndpointType::Person => "u",
150     EndpointType::Post => "post",
151     EndpointType::Comment => "comment",
152     EndpointType::PrivateMessage => "private_message",
153   };
154
155   Ok(Url::parse(&format!("{}/{}/{}", domain, point, name))?.into())
156 }
157
158 pub fn generate_followers_url(actor_id: &DbUrl) -> Result<DbUrl, ParseError> {
159   Ok(Url::parse(&format!("{}/followers", actor_id))?.into())
160 }
161
162 pub fn generate_inbox_url(actor_id: &DbUrl) -> Result<DbUrl, ParseError> {
163   Ok(Url::parse(&format!("{}/inbox", actor_id))?.into())
164 }
165
166 pub fn generate_site_inbox_url(actor_id: &DbUrl) -> Result<DbUrl, ParseError> {
167   let mut actor_id: Url = actor_id.clone().into();
168   actor_id.set_path("site_inbox");
169   Ok(actor_id.into())
170 }
171
172 pub fn generate_shared_inbox_url(actor_id: &DbUrl) -> Result<DbUrl, LemmyError> {
173   let actor_id: Url = actor_id.clone().into();
174   let url = format!(
175     "{}://{}{}/inbox",
176     &actor_id.scheme(),
177     &actor_id.host_str().context(location_info!())?,
178     if let Some(port) = actor_id.port() {
179       format!(":{}", port)
180     } else {
181       "".to_string()
182     },
183   );
184   Ok(Url::parse(&url)?.into())
185 }
186
187 pub fn generate_outbox_url(actor_id: &DbUrl) -> Result<DbUrl, ParseError> {
188   Ok(Url::parse(&format!("{}/outbox", actor_id))?.into())
189 }
190
191 fn generate_moderators_url(community_id: &DbUrl) -> Result<DbUrl, LemmyError> {
192   Ok(Url::parse(&format!("{}/moderators", community_id))?.into())
193 }
194
195 /// Store a sent or received activity in the database, for logging purposes. These records are not
196 /// persistent.
197 #[tracing::instrument(skip(pool))]
198 async fn insert_activity(
199   ap_id: &Url,
200   activity: serde_json::Value,
201   local: bool,
202   sensitive: bool,
203   pool: &DbPool,
204 ) -> Result<(), LemmyError> {
205   let ap_id = ap_id.to_owned().into();
206   blocking(pool, move |conn| {
207     Activity::insert(conn, ap_id, activity, local, sensitive)
208   })
209   .await??;
210   Ok(())
211 }