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