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