2 pub(crate) mod collections;
10 extern crate lazy_static;
12 use crate::fetcher::post_or_comment::PostOrComment;
13 use anyhow::{anyhow, Context};
14 use lemmy_api_common::blocking;
15 use lemmy_apub_lib::{activity_queue::send_activity, traits::ActorType};
16 use lemmy_db_schema::{
17 newtypes::{CommunityId, DbUrl},
18 source::{activity::Activity, person::Person},
21 use lemmy_db_views_actor::community_person_ban_view::CommunityPersonBanView;
22 use lemmy_utils::{location_info, settings::structs::Settings, LemmyError};
23 use lemmy_websocket::LemmyContext;
27 use url::{ParseError, Url};
29 /// Checks if the ID is allowed for sending or receiving.
31 /// In particular, it checks for:
32 /// - federation being enabled (if its disabled, only local URLs are allowed)
33 /// - the correct scheme (either http or https)
34 /// - URL being in the allowlist (if it is active)
35 /// - URL not being in the blocklist (if it is active)
37 pub(crate) fn check_is_apub_id_valid(
39 use_strict_allowlist: bool,
41 ) -> Result<(), LemmyError> {
42 let domain = apub_id.domain().context(location_info!())?.to_string();
43 let local_instance = settings.get_hostname_without_port()?;
45 if !settings.federation.enabled {
46 return if domain == local_instance {
51 "Trying to connect with {}, but federation is disabled",
59 let host = apub_id.host_str().context(location_info!())?;
60 let host_as_ip = host.parse::<IpAddr>();
61 if host == "localhost" || host_as_ip.is_ok() {
62 return Err(anyhow!("invalid hostname {}: {}", host, apub_id).into());
65 if apub_id.scheme() != settings.get_protocol_string() {
66 return Err(anyhow!("invalid apub id scheme {}: {}", apub_id.scheme(), apub_id).into());
69 // TODO: might be good to put the part above in one method, and below in another
70 // (which only gets called in apub::objects)
71 // -> no that doesnt make sense, we still need the code below for blocklist and strict allowlist
72 if let Some(blocked) = settings.to_owned().federation.blocked_instances {
73 if blocked.contains(&domain) {
74 return Err(anyhow!("{} is in federation blocklist", domain).into());
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 return Err(anyhow!("{} not in federation allowlist", domain).into());
95 #[async_trait::async_trait(?Send)]
96 pub trait CommunityType {
97 fn followers_url(&self) -> Url;
98 async fn get_follower_inboxes(
102 ) -> Result<Vec<Url>, LemmyError>;
105 pub enum EndpointType {
113 /// Generates an apub endpoint for a given domain, IE xyz.tld
114 fn generate_apub_endpoint_for_domain(
115 endpoint_type: EndpointType,
118 ) -> Result<DbUrl, ParseError> {
119 let point = match endpoint_type {
120 EndpointType::Community => "c",
121 EndpointType::Person => "u",
122 EndpointType::Post => "post",
123 EndpointType::Comment => "comment",
124 EndpointType::PrivateMessage => "private_message",
127 Ok(Url::parse(&format!("{}/{}/{}", domain, point, name))?.into())
130 /// Generates the ActivityPub ID for a given object type and ID.
131 pub fn generate_apub_endpoint(
132 endpoint_type: EndpointType,
134 protocol_and_hostname: &str,
135 ) -> Result<DbUrl, ParseError> {
136 generate_apub_endpoint_for_domain(endpoint_type, name, protocol_and_hostname)
139 pub fn generate_followers_url(actor_id: &DbUrl) -> Result<DbUrl, ParseError> {
140 Ok(Url::parse(&format!("{}/followers", actor_id))?.into())
143 pub fn generate_inbox_url(actor_id: &DbUrl) -> Result<DbUrl, ParseError> {
144 Ok(Url::parse(&format!("{}/inbox", actor_id))?.into())
147 pub fn generate_shared_inbox_url(actor_id: &DbUrl) -> Result<DbUrl, LemmyError> {
148 let actor_id: Url = actor_id.clone().into();
152 &actor_id.host_str().context(location_info!())?,
153 if let Some(port) = actor_id.port() {
159 Ok(Url::parse(&url)?.into())
162 pub fn generate_outbox_url(actor_id: &DbUrl) -> Result<DbUrl, ParseError> {
163 Ok(Url::parse(&format!("{}/outbox", actor_id))?.into())
166 fn generate_moderators_url(community_id: &DbUrl) -> Result<DbUrl, LemmyError> {
167 Ok(Url::parse(&format!("{}/moderators", community_id))?.into())
170 /// Takes in a shortname of the type dessalines@xyz.tld or dessalines (assumed to be local), and outputs the actor id.
171 /// Used in the API for communities and users.
172 pub fn build_actor_id_from_shortname(
173 endpoint_type: EndpointType,
176 ) -> Result<DbUrl, ParseError> {
177 let split = short_name.split('@').collect::<Vec<&str>>();
181 // If there's no @, its local
182 let domain = if split.len() == 1 {
183 settings.get_protocol_and_hostname()
185 format!("{}://{}", settings.get_protocol_string(), split[1])
188 generate_apub_endpoint_for_domain(endpoint_type, name, &domain)
191 /// Store a sent or received activity in the database, for logging purposes. These records are not
193 async fn insert_activity<T>(
199 ) -> Result<(), LemmyError>
201 T: Serialize + std::fmt::Debug + Send + 'static,
203 let ap_id = ap_id.to_owned().into();
204 blocking(pool, move |conn| {
205 Activity::insert(conn, ap_id, &activity, local, sensitive)
211 async fn check_community_or_site_ban(
213 community_id: CommunityId,
215 ) -> Result<(), LemmyError> {
217 return Err(anyhow!("Person is banned from site").into());
219 let person_id = person.id;
221 move |conn: &'_ _| CommunityPersonBanView::get(conn, person_id, community_id).is_ok();
222 if blocking(pool, is_banned).await? {
223 return Err(anyhow!("Person is banned from community").into());
229 pub(crate) async fn send_lemmy_activity<T: Serialize>(
230 context: &LemmyContext,
233 actor: &dyn ActorType,
236 ) -> Result<(), LemmyError> {
237 if !context.settings().federation.enabled || inboxes.is_empty() {
241 info!("Sending activity {}", activity_id.to_string());
243 // Don't send anything to ourselves
244 // TODO: this should be a debug assert
245 let hostname = context.settings().get_hostname_without_port()?;
246 let inboxes: Vec<&Url> = inboxes
248 .filter(|i| i.domain().expect("valid inbox url") != hostname)
251 let serialised_activity = serde_json::to_string(&activity)?;
255 serialised_activity.clone(),
267 context.activity_queue(),