1 use crate::fetcher::post_or_comment::PostOrComment;
2 use anyhow::{anyhow, Context};
3 use lemmy_api_common::utils::blocking;
4 use lemmy_db_schema::{newtypes::DbUrl, source::activity::Activity, utils::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;
20 /// Checks if the ID is allowed for sending or receiving.
22 /// In particular, it checks for:
23 /// - federation being enabled (if its disabled, only local URLs are allowed)
24 /// - the correct scheme (either http or https)
25 /// - URL being in the allowlist (if it is active)
26 /// - URL not being in the blocklist (if it is active)
28 /// `use_strict_allowlist` should be true only when parsing a remote community, or when parsing a
29 /// post/comment in a local community.
30 #[tracing::instrument(skip(settings))]
31 pub(crate) fn check_is_apub_id_valid(
33 use_strict_allowlist: bool,
35 ) -> Result<(), LemmyError> {
36 let domain = apub_id.domain().context(location_info!())?.to_string();
37 let local_instance = settings.get_hostname_without_port()?;
39 if !settings.federation.enabled {
40 return if domain == local_instance {
44 "Trying to connect with {}, but federation is disabled",
47 Err(LemmyError::from_error_message(err, "federation_disabled"))
51 let host = apub_id.host_str().context(location_info!())?;
52 let host_as_ip = host.parse::<IpAddr>();
53 if host == "localhost" || host_as_ip.is_ok() {
54 let err = anyhow!("invalid hostname {}: {}", host, apub_id);
55 return Err(LemmyError::from_error_message(err, "invalid_hostname"));
58 if apub_id.scheme() != settings.get_protocol_string() {
59 let err = anyhow!("invalid apub id scheme {}: {}", apub_id.scheme(), apub_id);
60 return Err(LemmyError::from_error_message(err, "invalid_scheme"));
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 let err = anyhow!("{} is in federation blocklist", domain);
69 return Err(LemmyError::from_error_message(err, "federation_blocked"));
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
79 allowed.push(local_instance);
81 if !allowed.contains(&domain) {
82 let err = anyhow!("{} not in federation allowlist", domain);
83 return Err(LemmyError::from_error_message(
85 "federation_not_allowed",
94 pub(crate) fn deserialize_one_or_many<'de, T, D>(deserializer: D) -> Result<Vec<T>, D::Error>
99 #[derive(Deserialize)]
106 let result: OneOrMany<T> = Deserialize::deserialize(deserializer)?;
108 OneOrMany::Many(list) => list,
109 OneOrMany::One(value) => vec![value],
113 pub(crate) fn deserialize_one<'de, T, D>(deserializer: D) -> Result<[T; 1], D::Error>
116 D: Deserializer<'de>,
118 #[derive(Deserialize)]
125 let result: MaybeArray<T> = Deserialize::deserialize(deserializer)?;
127 MaybeArray::Simple(value) => [value],
128 MaybeArray::Array(value) => value,
132 pub(crate) fn deserialize_skip_error<'de, T, D>(deserializer: D) -> Result<T, D::Error>
134 T: Deserialize<'de> + Default,
135 D: Deserializer<'de>,
137 let result = Deserialize::deserialize(deserializer);
140 Err(_) => Default::default(),
144 pub enum EndpointType {
152 /// Generates an apub endpoint for a given domain, IE xyz.tld
153 pub fn generate_local_apub_endpoint(
154 endpoint_type: EndpointType,
157 ) -> Result<DbUrl, ParseError> {
158 let point = match endpoint_type {
159 EndpointType::Community => "c",
160 EndpointType::Person => "u",
161 EndpointType::Post => "post",
162 EndpointType::Comment => "comment",
163 EndpointType::PrivateMessage => "private_message",
166 Ok(Url::parse(&format!("{}/{}/{}", domain, point, name))?.into())
169 pub fn generate_followers_url(actor_id: &DbUrl) -> Result<DbUrl, ParseError> {
170 Ok(Url::parse(&format!("{}/followers", actor_id))?.into())
173 pub fn generate_inbox_url(actor_id: &DbUrl) -> Result<DbUrl, ParseError> {
174 Ok(Url::parse(&format!("{}/inbox", actor_id))?.into())
177 pub fn generate_site_inbox_url(actor_id: &DbUrl) -> Result<DbUrl, ParseError> {
178 let mut actor_id: Url = actor_id.clone().into();
179 actor_id.set_path("site_inbox");
183 pub fn generate_shared_inbox_url(actor_id: &DbUrl) -> Result<DbUrl, LemmyError> {
184 let actor_id: Url = actor_id.clone().into();
188 &actor_id.host_str().context(location_info!())?,
189 if let Some(port) = actor_id.port() {
195 Ok(Url::parse(&url)?.into())
198 pub fn generate_outbox_url(actor_id: &DbUrl) -> Result<DbUrl, ParseError> {
199 Ok(Url::parse(&format!("{}/outbox", actor_id))?.into())
202 fn generate_moderators_url(community_id: &DbUrl) -> Result<DbUrl, LemmyError> {
203 Ok(Url::parse(&format!("{}/moderators", community_id))?.into())
206 /// Store a sent or received activity in the database, for logging purposes. These records are not
208 #[tracing::instrument(skip(pool))]
209 async fn insert_activity(
211 activity: serde_json::Value,
215 ) -> Result<bool, LemmyError> {
216 let ap_id = ap_id.to_owned().into();
218 blocking(pool, move |conn| {
219 Activity::insert(conn, ap_id, activity, local, sensitive)