]> Untitled Git - lemmy.git/blob - crates/apub/src/lib.rs
Don't drop error context when adding a message to errors (#1958)
[lemmy.git] / crates / apub / src / lib.rs
1 use crate::fetcher::post_or_comment::PostOrComment;
2 use 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 error = LemmyError::from(anyhow::anyhow!(
45         "Trying to connect with {}, but federation is disabled",
46         domain
47       ));
48       Err(error.with_message("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 error = LemmyError::from(anyhow::anyhow!("invalid hostname {}: {}", host, apub_id));
56     return Err(error.with_message("invalid_hostname"));
57   }
58
59   if apub_id.scheme() != settings.get_protocol_string() {
60     let error = LemmyError::from(anyhow::anyhow!(
61       "invalid apub id scheme {}: {}",
62       apub_id.scheme(),
63       apub_id
64     ));
65     return Err(error.with_message("invalid_scheme"));
66   }
67
68   // TODO: might be good to put the part above in one method, and below in another
69   //       (which only gets called in apub::objects)
70   //        -> no that doesnt make sense, we still need the code below for blocklist and strict allowlist
71   if let Some(blocked) = settings.to_owned().federation.blocked_instances {
72     if blocked.contains(&domain) {
73       let error = LemmyError::from(anyhow::anyhow!("{} is in federation blocklist", domain));
74       return Err(error.with_message("federation_blocked"));
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         let error = LemmyError::from(anyhow::anyhow!("{} not in federation allowlist", domain));
88         return Err(error.with_message("federation_not_allowed"));
89       }
90     }
91   }
92
93   Ok(())
94 }
95
96 pub(crate) fn deserialize_one_or_many<'de, T, D>(deserializer: D) -> Result<Vec<T>, D::Error>
97 where
98   T: Deserialize<'de>,
99   D: Deserializer<'de>,
100 {
101   #[derive(Deserialize)]
102   #[serde(untagged)]
103   enum OneOrMany<T> {
104     One(T),
105     Many(Vec<T>),
106   }
107
108   let result: OneOrMany<T> = Deserialize::deserialize(deserializer)?;
109   Ok(match result {
110     OneOrMany::Many(list) => list,
111     OneOrMany::One(value) => vec![value],
112   })
113 }
114
115 pub enum EndpointType {
116   Community,
117   Person,
118   Post,
119   Comment,
120   PrivateMessage,
121 }
122
123 /// Generates an apub endpoint for a given domain, IE xyz.tld
124 pub fn generate_local_apub_endpoint(
125   endpoint_type: EndpointType,
126   name: &str,
127   domain: &str,
128 ) -> Result<DbUrl, ParseError> {
129   let point = match endpoint_type {
130     EndpointType::Community => "c",
131     EndpointType::Person => "u",
132     EndpointType::Post => "post",
133     EndpointType::Comment => "comment",
134     EndpointType::PrivateMessage => "private_message",
135   };
136
137   Ok(Url::parse(&format!("{}/{}/{}", domain, point, name))?.into())
138 }
139
140 pub fn generate_followers_url(actor_id: &DbUrl) -> Result<DbUrl, ParseError> {
141   Ok(Url::parse(&format!("{}/followers", actor_id))?.into())
142 }
143
144 pub fn generate_inbox_url(actor_id: &DbUrl) -> Result<DbUrl, ParseError> {
145   Ok(Url::parse(&format!("{}/inbox", actor_id))?.into())
146 }
147
148 pub fn generate_shared_inbox_url(actor_id: &DbUrl) -> Result<DbUrl, LemmyError> {
149   let actor_id: Url = actor_id.clone().into();
150   let url = format!(
151     "{}://{}{}/inbox",
152     &actor_id.scheme(),
153     &actor_id.host_str().context(location_info!())?,
154     if let Some(port) = actor_id.port() {
155       format!(":{}", port)
156     } else {
157       "".to_string()
158     },
159   );
160   Ok(Url::parse(&url)?.into())
161 }
162
163 pub fn generate_outbox_url(actor_id: &DbUrl) -> Result<DbUrl, ParseError> {
164   Ok(Url::parse(&format!("{}/outbox", actor_id))?.into())
165 }
166
167 fn generate_moderators_url(community_id: &DbUrl) -> Result<DbUrl, LemmyError> {
168   Ok(Url::parse(&format!("{}/moderators", community_id))?.into())
169 }
170
171 /// Store a sent or received activity in the database, for logging purposes. These records are not
172 /// persistent.
173 #[tracing::instrument(skip(pool))]
174 async fn insert_activity(
175   ap_id: &Url,
176   activity: serde_json::Value,
177   local: bool,
178   sensitive: bool,
179   pool: &DbPool,
180 ) -> Result<(), LemmyError> {
181   let ap_id = ap_id.to_owned().into();
182   blocking(pool, move |conn| {
183     Activity::insert(conn, ap_id, activity, local, sensitive)
184   })
185   .await??;
186   Ok(())
187 }