1 use crate::fetcher::post_or_comment::PostOrComment;
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 serde::{Deserialize, Deserializer};
8 use url::{ParseError, Url};
11 pub(crate) mod activity_lists;
12 pub(crate) mod collections;
16 pub(crate) mod mentions;
21 /// Checks if the ID is allowed for sending or receiving.
23 /// In particular, it checks for:
24 /// - federation being enabled (if its disabled, only local URLs are allowed)
25 /// - the correct scheme (either http or https)
26 /// - URL being in the allowlist (if it is active)
27 /// - URL not being in the blocklist (if it is active)
29 /// `use_strict_allowlist` should be true only when parsing a remote community, or when parsing a
30 /// post/comment in a local community.
31 #[tracing::instrument(skip(settings))]
32 pub(crate) fn check_is_apub_id_valid(
34 use_strict_allowlist: bool,
36 ) -> Result<(), LemmyError> {
37 let domain = apub_id.domain().context(location_info!())?.to_string();
38 let local_instance = settings.get_hostname_without_port()?;
40 if !settings.federation.enabled {
41 return if domain == local_instance {
44 let error = LemmyError::from(anyhow::anyhow!(
45 "Trying to connect with {}, but federation is disabled",
48 Err(error.with_message("federation_disabled"))
52 let host = apub_id.host_str().context(location_info!())?;
53 let host_as_ip = host.parse::<IpAddr>();
54 if host == "localhost" || host_as_ip.is_ok() {
55 let error = LemmyError::from(anyhow::anyhow!("invalid hostname {}: {}", host, apub_id));
56 return Err(error.with_message("invalid_hostname"));
59 if apub_id.scheme() != settings.get_protocol_string() {
60 let error = LemmyError::from(anyhow::anyhow!(
61 "invalid apub id scheme {}: {}",
65 return Err(error.with_message("invalid_scheme"));
68 // TODO: might be good to put the part above in one method, and below in another
69 // (which only gets called in apub::objects)
70 // -> no that doesnt make sense, we still need the code below for blocklist and strict allowlist
71 if let Some(blocked) = settings.to_owned().federation.blocked_instances {
72 if blocked.contains(&domain) {
73 let error = LemmyError::from(anyhow::anyhow!("{} is in federation blocklist", domain));
74 return Err(error.with_message("federation_blocked"));
78 if let Some(mut allowed) = settings.to_owned().federation.allowed_instances {
79 // Only check allowlist if this is a community, or strict allowlist is enabled.
80 let strict_allowlist = settings.to_owned().federation.strict_allowlist;
81 if use_strict_allowlist || strict_allowlist {
82 // need to allow this explicitly because apub receive might contain objects from our local
84 allowed.push(local_instance);
86 if !allowed.contains(&domain) {
87 let error = LemmyError::from(anyhow::anyhow!("{} not in federation allowlist", domain));
88 return Err(error.with_message("federation_not_allowed"));
96 pub(crate) fn deserialize_one_or_many<'de, T, D>(deserializer: D) -> Result<Vec<T>, D::Error>
101 #[derive(Deserialize)]
108 let result: OneOrMany<T> = Deserialize::deserialize(deserializer)?;
110 OneOrMany::Many(list) => list,
111 OneOrMany::One(value) => vec![value],
115 pub(crate) fn deserialize_one<'de, T, D>(deserializer: D) -> Result<[T; 1], D::Error>
118 D: Deserializer<'de>,
120 #[derive(Deserialize)]
127 let result: MaybeArray<T> = Deserialize::deserialize(deserializer)?;
129 MaybeArray::Simple(value) => [value],
130 MaybeArray::Array(value) => value,
134 pub enum EndpointType {
142 /// Generates an apub endpoint for a given domain, IE xyz.tld
143 pub fn generate_local_apub_endpoint(
144 endpoint_type: EndpointType,
147 ) -> Result<DbUrl, ParseError> {
148 let point = match endpoint_type {
149 EndpointType::Community => "c",
150 EndpointType::Person => "u",
151 EndpointType::Post => "post",
152 EndpointType::Comment => "comment",
153 EndpointType::PrivateMessage => "private_message",
156 Ok(Url::parse(&format!("{}/{}/{}", domain, point, name))?.into())
159 pub fn generate_followers_url(actor_id: &DbUrl) -> Result<DbUrl, ParseError> {
160 Ok(Url::parse(&format!("{}/followers", actor_id))?.into())
163 pub fn generate_inbox_url(actor_id: &DbUrl) -> Result<DbUrl, ParseError> {
164 Ok(Url::parse(&format!("{}/inbox", actor_id))?.into())
167 pub fn generate_shared_inbox_url(actor_id: &DbUrl) -> Result<DbUrl, LemmyError> {
168 let actor_id: Url = actor_id.clone().into();
172 &actor_id.host_str().context(location_info!())?,
173 if let Some(port) = actor_id.port() {
179 Ok(Url::parse(&url)?.into())
182 pub fn generate_outbox_url(actor_id: &DbUrl) -> Result<DbUrl, ParseError> {
183 Ok(Url::parse(&format!("{}/outbox", actor_id))?.into())
186 fn generate_moderators_url(community_id: &DbUrl) -> Result<DbUrl, LemmyError> {
187 Ok(Url::parse(&format!("{}/moderators", community_id))?.into())
190 /// Store a sent or received activity in the database, for logging purposes. These records are not
192 #[tracing::instrument(skip(pool))]
193 async fn insert_activity(
195 activity: serde_json::Value,
199 ) -> Result<(), LemmyError> {
200 let ap_id = ap_id.to_owned().into();
201 blocking(pool, move |conn| {
202 Activity::insert(conn, ap_id, activity, local, sensitive)