]> Untitled Git - lemmy.git/blob - crates/apub/src/lib.rs
b3c7eff7218beff461f19189b6c8f49db824a41a
[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 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       Err(
44         anyhow!(
45           "Trying to connect with {}, but federation is disabled",
46           domain
47         )
48         .into(),
49       )
50     };
51   }
52
53   let host = apub_id.host_str().context(location_info!())?;
54   let host_as_ip = host.parse::<IpAddr>();
55   if host == "localhost" || host_as_ip.is_ok() {
56     return Err(anyhow!("invalid hostname {}: {}", host, apub_id).into());
57   }
58
59   if apub_id.scheme() != settings.get_protocol_string() {
60     return Err(anyhow!("invalid apub id scheme {}: {}", apub_id.scheme(), apub_id).into());
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       return Err(anyhow!("{} is in federation blocklist", domain).into());
69     }
70   }
71
72   if let Some(mut allowed) = settings.to_owned().federation.allowed_instances {
73     // Only check allowlist if this is a community, or strict allowlist is enabled.
74     let strict_allowlist = settings.to_owned().federation.strict_allowlist;
75     if use_strict_allowlist || strict_allowlist {
76       // need to allow this explicitly because apub receive might contain objects from our local
77       // instance.
78       allowed.push(local_instance);
79
80       if !allowed.contains(&domain) {
81         return Err(anyhow!("{} not in federation allowlist", domain).into());
82       }
83     }
84   }
85
86   Ok(())
87 }
88
89 pub(crate) fn deserialize_one_or_many<'de, T, D>(deserializer: D) -> Result<Vec<T>, D::Error>
90 where
91   T: Deserialize<'de>,
92   D: Deserializer<'de>,
93 {
94   #[derive(Deserialize)]
95   #[serde(untagged)]
96   enum OneOrMany<T> {
97     One(T),
98     Many(Vec<T>),
99   }
100
101   let result: OneOrMany<T> = Deserialize::deserialize(deserializer)?;
102   Ok(match result {
103     OneOrMany::Many(list) => list,
104     OneOrMany::One(value) => vec![value],
105   })
106 }
107
108 pub enum EndpointType {
109   Community,
110   Person,
111   Post,
112   Comment,
113   PrivateMessage,
114 }
115
116 /// Generates an apub endpoint for a given domain, IE xyz.tld
117 pub fn generate_local_apub_endpoint(
118   endpoint_type: EndpointType,
119   name: &str,
120   domain: &str,
121 ) -> Result<DbUrl, ParseError> {
122   let point = match endpoint_type {
123     EndpointType::Community => "c",
124     EndpointType::Person => "u",
125     EndpointType::Post => "post",
126     EndpointType::Comment => "comment",
127     EndpointType::PrivateMessage => "private_message",
128   };
129
130   Ok(Url::parse(&format!("{}/{}/{}", domain, point, name))?.into())
131 }
132
133 pub fn generate_followers_url(actor_id: &DbUrl) -> Result<DbUrl, ParseError> {
134   Ok(Url::parse(&format!("{}/followers", actor_id))?.into())
135 }
136
137 pub fn generate_inbox_url(actor_id: &DbUrl) -> Result<DbUrl, ParseError> {
138   Ok(Url::parse(&format!("{}/inbox", actor_id))?.into())
139 }
140
141 pub fn generate_shared_inbox_url(actor_id: &DbUrl) -> Result<DbUrl, LemmyError> {
142   let actor_id: Url = actor_id.clone().into();
143   let url = format!(
144     "{}://{}{}/inbox",
145     &actor_id.scheme(),
146     &actor_id.host_str().context(location_info!())?,
147     if let Some(port) = actor_id.port() {
148       format!(":{}", port)
149     } else {
150       "".to_string()
151     },
152   );
153   Ok(Url::parse(&url)?.into())
154 }
155
156 pub fn generate_outbox_url(actor_id: &DbUrl) -> Result<DbUrl, ParseError> {
157   Ok(Url::parse(&format!("{}/outbox", actor_id))?.into())
158 }
159
160 fn generate_moderators_url(community_id: &DbUrl) -> Result<DbUrl, LemmyError> {
161   Ok(Url::parse(&format!("{}/moderators", community_id))?.into())
162 }
163
164 /// Store a sent or received activity in the database, for logging purposes. These records are not
165 /// persistent.
166 async fn insert_activity(
167   ap_id: &Url,
168   activity: serde_json::Value,
169   local: bool,
170   sensitive: bool,
171   pool: &DbPool,
172 ) -> Result<(), LemmyError> {
173   let ap_id = ap_id.to_owned().into();
174   blocking(pool, move |conn| {
175     Activity::insert(conn, ap_id, activity, local, sensitive)
176   })
177   .await??;
178   Ok(())
179 }