]> Untitled Git - lemmy.git/blob - crates/apub/src/lib.rs
Implement instance actor (#1798)
[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(crate) fn deserialize_one<'de, T, D>(deserializer: D) -> Result<[T; 1], D::Error>
116 where
117   T: Deserialize<'de>,
118   D: Deserializer<'de>,
119 {
120   #[derive(Deserialize)]
121   #[serde(untagged)]
122   enum MaybeArray<T> {
123     Simple(T),
124     Array([T; 1]),
125   }
126
127   let result: MaybeArray<T> = Deserialize::deserialize(deserializer)?;
128   Ok(match result {
129     MaybeArray::Simple(value) => [value],
130     MaybeArray::Array(value) => value,
131   })
132 }
133
134 pub enum EndpointType {
135   Community,
136   Person,
137   Post,
138   Comment,
139   PrivateMessage,
140 }
141
142 /// Generates an apub endpoint for a given domain, IE xyz.tld
143 pub fn generate_local_apub_endpoint(
144   endpoint_type: EndpointType,
145   name: &str,
146   domain: &str,
147 ) -> Result<DbUrl, ParseError> {
148   let point = match endpoint_type {
149     EndpointType::Community => "c",
150     EndpointType::Person => "u",
151     EndpointType::Post => "post",
152     EndpointType::Comment => "comment",
153     EndpointType::PrivateMessage => "private_message",
154   };
155
156   Ok(Url::parse(&format!("{}/{}/{}", domain, point, name))?.into())
157 }
158
159 pub fn generate_followers_url(actor_id: &DbUrl) -> Result<DbUrl, ParseError> {
160   Ok(Url::parse(&format!("{}/followers", actor_id))?.into())
161 }
162
163 pub fn generate_inbox_url(actor_id: &DbUrl) -> Result<DbUrl, ParseError> {
164   Ok(Url::parse(&format!("{}/inbox", actor_id))?.into())
165 }
166
167 pub fn generate_site_inbox_url(actor_id: &DbUrl) -> Result<DbUrl, ParseError> {
168   let mut actor_id: Url = actor_id.clone().into();
169   actor_id.set_path("site_inbox");
170   Ok(actor_id.into())
171 }
172
173 pub fn generate_shared_inbox_url(actor_id: &DbUrl) -> Result<DbUrl, LemmyError> {
174   let actor_id: Url = actor_id.clone().into();
175   let url = format!(
176     "{}://{}{}/inbox",
177     &actor_id.scheme(),
178     &actor_id.host_str().context(location_info!())?,
179     if let Some(port) = actor_id.port() {
180       format!(":{}", port)
181     } else {
182       "".to_string()
183     },
184   );
185   Ok(Url::parse(&url)?.into())
186 }
187
188 pub fn generate_outbox_url(actor_id: &DbUrl) -> Result<DbUrl, ParseError> {
189   Ok(Url::parse(&format!("{}/outbox", actor_id))?.into())
190 }
191
192 fn generate_moderators_url(community_id: &DbUrl) -> Result<DbUrl, LemmyError> {
193   Ok(Url::parse(&format!("{}/moderators", community_id))?.into())
194 }
195
196 /// Store a sent or received activity in the database, for logging purposes. These records are not
197 /// persistent.
198 #[tracing::instrument(skip(pool))]
199 async fn insert_activity(
200   ap_id: &Url,
201   activity: serde_json::Value,
202   local: bool,
203   sensitive: bool,
204   pool: &DbPool,
205 ) -> Result<(), LemmyError> {
206   let ap_id = ap_id.to_owned().into();
207   blocking(pool, move |conn| {
208     Activity::insert(conn, ap_id, activity, local, sensitive)
209   })
210   .await??;
211   Ok(())
212 }