]> Untitled Git - lemmy.git/blob - crates/apub/src/lib.rs
Merge pull request #1938 from LemmyNet/once_cell
[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 std::net::IpAddr;
7 use url::{ParseError, Url};
8
9 pub mod activities;
10 pub(crate) mod activity_lists;
11 pub(crate) mod collections;
12 mod context;
13 pub mod fetcher;
14 pub mod http;
15 pub(crate) mod mentions;
16 pub mod migrations;
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 pub(crate) fn check_is_apub_id_valid(
31   apub_id: &Url,
32   use_strict_allowlist: bool,
33   settings: &Settings,
34 ) -> Result<(), LemmyError> {
35   let domain = apub_id.domain().context(location_info!())?.to_string();
36   let local_instance = settings.get_hostname_without_port()?;
37
38   if !settings.federation.enabled {
39     return if domain == local_instance {
40       Ok(())
41     } else {
42       Err(
43         anyhow!(
44           "Trying to connect with {}, but federation is disabled",
45           domain
46         )
47         .into(),
48       )
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     return Err(anyhow!("invalid hostname {}: {}", host, apub_id).into());
56   }
57
58   if apub_id.scheme() != settings.get_protocol_string() {
59     return Err(anyhow!("invalid apub id scheme {}: {}", apub_id.scheme(), apub_id).into());
60   }
61
62   // TODO: might be good to put the part above in one method, and below in another
63   //       (which only gets called in apub::objects)
64   //        -> no that doesnt make sense, we still need the code below for blocklist and strict allowlist
65   if let Some(blocked) = settings.to_owned().federation.blocked_instances {
66     if blocked.contains(&domain) {
67       return Err(anyhow!("{} is in federation blocklist", domain).into());
68     }
69   }
70
71   if let Some(mut allowed) = settings.to_owned().federation.allowed_instances {
72     // Only check allowlist if this is a community, or strict allowlist is enabled.
73     let strict_allowlist = settings.to_owned().federation.strict_allowlist;
74     if use_strict_allowlist || strict_allowlist {
75       // need to allow this explicitly because apub receive might contain objects from our local
76       // instance.
77       allowed.push(local_instance);
78
79       if !allowed.contains(&domain) {
80         return Err(anyhow!("{} not in federation allowlist", domain).into());
81       }
82     }
83   }
84
85   Ok(())
86 }
87
88 pub enum EndpointType {
89   Community,
90   Person,
91   Post,
92   Comment,
93   PrivateMessage,
94 }
95
96 /// Generates an apub endpoint for a given domain, IE xyz.tld
97 pub fn generate_local_apub_endpoint(
98   endpoint_type: EndpointType,
99   name: &str,
100   domain: &str,
101 ) -> Result<DbUrl, ParseError> {
102   let point = match endpoint_type {
103     EndpointType::Community => "c",
104     EndpointType::Person => "u",
105     EndpointType::Post => "post",
106     EndpointType::Comment => "comment",
107     EndpointType::PrivateMessage => "private_message",
108   };
109
110   Ok(Url::parse(&format!("{}/{}/{}", domain, point, name))?.into())
111 }
112
113 pub fn generate_followers_url(actor_id: &DbUrl) -> Result<DbUrl, ParseError> {
114   Ok(Url::parse(&format!("{}/followers", actor_id))?.into())
115 }
116
117 pub fn generate_inbox_url(actor_id: &DbUrl) -> Result<DbUrl, ParseError> {
118   Ok(Url::parse(&format!("{}/inbox", actor_id))?.into())
119 }
120
121 pub fn generate_shared_inbox_url(actor_id: &DbUrl) -> Result<DbUrl, LemmyError> {
122   let actor_id: Url = actor_id.clone().into();
123   let url = format!(
124     "{}://{}{}/inbox",
125     &actor_id.scheme(),
126     &actor_id.host_str().context(location_info!())?,
127     if let Some(port) = actor_id.port() {
128       format!(":{}", port)
129     } else {
130       "".to_string()
131     },
132   );
133   Ok(Url::parse(&url)?.into())
134 }
135
136 pub fn generate_outbox_url(actor_id: &DbUrl) -> Result<DbUrl, ParseError> {
137   Ok(Url::parse(&format!("{}/outbox", actor_id))?.into())
138 }
139
140 fn generate_moderators_url(community_id: &DbUrl) -> Result<DbUrl, LemmyError> {
141   Ok(Url::parse(&format!("{}/moderators", community_id))?.into())
142 }
143
144 /// Store a sent or received activity in the database, for logging purposes. These records are not
145 /// persistent.
146 async fn insert_activity(
147   ap_id: &Url,
148   activity: serde_json::Value,
149   local: bool,
150   sensitive: bool,
151   pool: &DbPool,
152 ) -> Result<(), LemmyError> {
153   let ap_id = ap_id.to_owned().into();
154   blocking(pool, move |conn| {
155     Activity::insert(conn, ap_id, activity, local, sensitive)
156   })
157   .await??;
158   Ok(())
159 }