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