]> Untitled Git - lemmy.git/blob - crates/apub/src/lib.rs
74dfd95256a89e0e20a136e028fac33f705cf443
[lemmy.git] / crates / apub / src / lib.rs
1 pub mod activities;
2 pub(crate) mod activity_lists;
3 pub(crate) mod collections;
4 mod context;
5 pub mod fetcher;
6 pub mod http;
7 pub mod migrations;
8 pub mod objects;
9 pub mod protocol;
10
11 #[macro_use]
12 extern crate lazy_static;
13
14 use crate::fetcher::post_or_comment::PostOrComment;
15 use anyhow::{anyhow, Context};
16 use lemmy_api_common::blocking;
17 use lemmy_apub_lib::webfinger::{webfinger_resolve_actor, WebfingerType};
18 use lemmy_db_schema::{newtypes::DbUrl, source::activity::Activity, DbPool};
19 use lemmy_utils::{location_info, settings::structs::Settings, LemmyError};
20 use lemmy_websocket::LemmyContext;
21 use serde::Serialize;
22 use std::net::IpAddr;
23 use url::{ParseError, Url};
24
25 /// Checks if the ID is allowed for sending or receiving.
26 ///
27 /// In particular, it checks for:
28 /// - federation being enabled (if its disabled, only local URLs are allowed)
29 /// - the correct scheme (either http or https)
30 /// - URL being in the allowlist (if it is active)
31 /// - URL not being in the blocklist (if it is active)
32 ///
33 /// `use_strict_allowlist` should be true only when parsing a remote community, or when parsing a
34 /// post/comment in a local community.
35 pub(crate) fn check_is_apub_id_valid(
36   apub_id: &Url,
37   use_strict_allowlist: bool,
38   settings: &Settings,
39 ) -> Result<(), LemmyError> {
40   let domain = apub_id.domain().context(location_info!())?.to_string();
41   let local_instance = settings.get_hostname_without_port()?;
42
43   if !settings.federation.enabled {
44     return if domain == local_instance {
45       Ok(())
46     } else {
47       Err(
48         anyhow!(
49           "Trying to connect with {}, but federation is disabled",
50           domain
51         )
52         .into(),
53       )
54     };
55   }
56
57   let host = apub_id.host_str().context(location_info!())?;
58   let host_as_ip = host.parse::<IpAddr>();
59   if host == "localhost" || host_as_ip.is_ok() {
60     return Err(anyhow!("invalid hostname {}: {}", host, apub_id).into());
61   }
62
63   if apub_id.scheme() != settings.get_protocol_string() {
64     return Err(anyhow!("invalid apub id scheme {}: {}", apub_id.scheme(), apub_id).into());
65   }
66
67   // TODO: might be good to put the part above in one method, and below in another
68   //       (which only gets called in apub::objects)
69   //        -> no that doesnt make sense, we still need the code below for blocklist and strict allowlist
70   if let Some(blocked) = settings.to_owned().federation.blocked_instances {
71     if blocked.contains(&domain) {
72       return Err(anyhow!("{} is in federation blocklist", domain).into());
73     }
74   }
75
76   if let Some(mut allowed) = settings.to_owned().federation.allowed_instances {
77     // Only check allowlist if this is a community, or strict allowlist is enabled.
78     let strict_allowlist = settings.to_owned().federation.strict_allowlist;
79     if use_strict_allowlist || strict_allowlist {
80       // need to allow this explicitly because apub receive might contain objects from our local
81       // instance.
82       allowed.push(local_instance);
83
84       if !allowed.contains(&domain) {
85         return Err(anyhow!("{} not in federation allowlist", domain).into());
86       }
87     }
88   }
89
90   Ok(())
91 }
92
93 pub enum EndpointType {
94   Community,
95   Person,
96   Post,
97   Comment,
98   PrivateMessage,
99 }
100
101 /// Generates an apub endpoint for a given domain, IE xyz.tld
102 pub fn generate_local_apub_endpoint(
103   endpoint_type: EndpointType,
104   name: &str,
105   domain: &str,
106 ) -> Result<DbUrl, ParseError> {
107   let point = match endpoint_type {
108     EndpointType::Community => "c",
109     EndpointType::Person => "u",
110     EndpointType::Post => "post",
111     EndpointType::Comment => "comment",
112     EndpointType::PrivateMessage => "private_message",
113   };
114
115   Ok(Url::parse(&format!("{}/{}/{}", domain, point, name))?.into())
116 }
117
118 pub fn generate_followers_url(actor_id: &DbUrl) -> Result<DbUrl, ParseError> {
119   Ok(Url::parse(&format!("{}/followers", actor_id))?.into())
120 }
121
122 pub fn generate_inbox_url(actor_id: &DbUrl) -> Result<DbUrl, ParseError> {
123   Ok(Url::parse(&format!("{}/inbox", actor_id))?.into())
124 }
125
126 pub fn generate_shared_inbox_url(actor_id: &DbUrl) -> Result<DbUrl, LemmyError> {
127   let actor_id: Url = actor_id.clone().into();
128   let url = format!(
129     "{}://{}{}/inbox",
130     &actor_id.scheme(),
131     &actor_id.host_str().context(location_info!())?,
132     if let Some(port) = actor_id.port() {
133       format!(":{}", port)
134     } else {
135       "".to_string()
136     },
137   );
138   Ok(Url::parse(&url)?.into())
139 }
140
141 pub fn generate_outbox_url(actor_id: &DbUrl) -> Result<DbUrl, ParseError> {
142   Ok(Url::parse(&format!("{}/outbox", actor_id))?.into())
143 }
144
145 fn generate_moderators_url(community_id: &DbUrl) -> Result<DbUrl, LemmyError> {
146   Ok(Url::parse(&format!("{}/moderators", community_id))?.into())
147 }
148
149 /// Takes in a shortname of the type dessalines@xyz.tld or dessalines (assumed to be local), and outputs the actor id.
150 /// Used in the API for communities and users.
151 pub async fn get_actor_id_from_name(
152   webfinger_type: WebfingerType,
153   short_name: &str,
154   context: &LemmyContext,
155 ) -> Result<DbUrl, LemmyError> {
156   let split = short_name.split('@').collect::<Vec<&str>>();
157
158   let name = split[0];
159
160   // If there's no @, its local
161   if split.len() == 1 {
162     let domain = context.settings().get_protocol_and_hostname();
163     let endpoint_type = match webfinger_type {
164       WebfingerType::Person => EndpointType::Person,
165       WebfingerType::Group => EndpointType::Community,
166     };
167     Ok(generate_local_apub_endpoint(endpoint_type, name, &domain)?)
168   } else {
169     let protocol = context.settings().get_protocol_string();
170     Ok(
171       webfinger_resolve_actor(name, split[1], webfinger_type, context.client(), protocol)
172         .await?
173         .into(),
174     )
175   }
176 }
177
178 /// Store a sent or received activity in the database, for logging purposes. These records are not
179 /// persistent.
180 async fn insert_activity<T>(
181   ap_id: &Url,
182   activity: &T,
183   local: bool,
184   sensitive: bool,
185   pool: &DbPool,
186 ) -> Result<(), LemmyError>
187 where
188   T: Serialize + std::fmt::Debug + Send + 'static,
189 {
190   let data = serde_json::to_value(activity)?;
191   let ap_id = ap_id.to_owned().into();
192   blocking(pool, move |conn| {
193     Activity::insert(conn, ap_id, data, local, sensitive)
194   })
195   .await??;
196   Ok(())
197 }