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