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