8 use crate::fetcher::post_or_comment::PostOrComment;
9 use anyhow::{anyhow, Context};
10 use lemmy_api_common::blocking;
11 use lemmy_apub_lib::{activity_queue::send_activity, traits::ActorType};
12 use lemmy_db_queries::{source::activity::Activity_, DbPool};
13 use lemmy_db_schema::{
14 source::{activity::Activity, person::Person},
18 use lemmy_db_views_actor::community_person_ban_view::CommunityPersonBanView;
19 use lemmy_utils::{location_info, settings::structs::Settings, LemmyError};
20 use lemmy_websocket::LemmyContext;
24 use url::{ParseError, Url};
26 /// Checks if the ID is allowed for sending or receiving.
28 /// In particular, it checks for:
29 /// - federation being enabled (if its disabled, only local URLs are allowed)
30 /// - the correct scheme (either http or https)
31 /// - URL being in the allowlist (if it is active)
32 /// - URL not being in the blocklist (if it is active)
34 pub(crate) fn check_is_apub_id_valid(
36 use_strict_allowlist: bool,
38 ) -> Result<(), LemmyError> {
39 let domain = apub_id.domain().context(location_info!())?.to_string();
40 let local_instance = settings.get_hostname_without_port()?;
42 if !settings.federation.enabled {
43 return if domain == local_instance {
48 "Trying to connect with {}, but federation is disabled",
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());
62 if apub_id.scheme() != settings.get_protocol_string() {
63 return Err(anyhow!("invalid apub id scheme {}: {}", apub_id.scheme(), apub_id).into());
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());
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
81 allowed.push(local_instance);
83 if !allowed.contains(&domain) {
84 return Err(anyhow!("{} not in federation allowlist", domain).into());
92 #[async_trait::async_trait(?Send)]
93 pub trait CommunityType {
94 fn followers_url(&self) -> Url;
95 async fn get_follower_inboxes(
99 ) -> Result<Vec<Url>, LemmyError>;
102 pub enum EndpointType {
110 /// Generates an apub endpoint for a given domain, IE xyz.tld
111 fn generate_apub_endpoint_for_domain(
112 endpoint_type: EndpointType,
115 ) -> Result<DbUrl, ParseError> {
116 let point = match endpoint_type {
117 EndpointType::Community => "c",
118 EndpointType::Person => "u",
119 EndpointType::Post => "post",
120 EndpointType::Comment => "comment",
121 EndpointType::PrivateMessage => "private_message",
124 Ok(Url::parse(&format!("{}/{}/{}", domain, point, name))?.into())
127 /// Generates the ActivityPub ID for a given object type and ID.
128 pub fn generate_apub_endpoint(
129 endpoint_type: EndpointType,
131 protocol_and_hostname: &str,
132 ) -> Result<DbUrl, ParseError> {
133 generate_apub_endpoint_for_domain(endpoint_type, name, protocol_and_hostname)
136 pub fn generate_followers_url(actor_id: &DbUrl) -> Result<DbUrl, ParseError> {
137 Ok(Url::parse(&format!("{}/followers", actor_id))?.into())
140 pub fn generate_inbox_url(actor_id: &DbUrl) -> Result<DbUrl, ParseError> {
141 Ok(Url::parse(&format!("{}/inbox", actor_id))?.into())
144 pub fn generate_shared_inbox_url(actor_id: &DbUrl) -> Result<DbUrl, LemmyError> {
145 let actor_id: Url = actor_id.clone().into();
149 &actor_id.host_str().context(location_info!())?,
150 if let Some(port) = actor_id.port() {
156 Ok(Url::parse(&url)?.into())
159 pub fn generate_outbox_url(actor_id: &DbUrl) -> Result<DbUrl, ParseError> {
160 Ok(Url::parse(&format!("{}/outbox", actor_id))?.into())
163 fn generate_moderators_url(community_id: &DbUrl) -> Result<DbUrl, LemmyError> {
164 Ok(Url::parse(&format!("{}/moderators", community_id))?.into())
167 /// Takes in a shortname of the type dessalines@xyz.tld or dessalines (assumed to be local), and outputs the actor id.
168 /// Used in the API for communities and users.
169 pub fn build_actor_id_from_shortname(
170 endpoint_type: EndpointType,
173 ) -> Result<DbUrl, ParseError> {
174 let split = short_name.split('@').collect::<Vec<&str>>();
178 // If there's no @, its local
179 let domain = if split.len() == 1 {
180 settings.get_protocol_and_hostname()
182 format!("{}://{}", settings.get_protocol_string(), split[1])
185 generate_apub_endpoint_for_domain(endpoint_type, name, &domain)
188 /// Store a sent or received activity in the database, for logging purposes. These records are not
190 async fn insert_activity<T>(
196 ) -> Result<(), LemmyError>
198 T: Serialize + std::fmt::Debug + Send + 'static,
200 let ap_id = ap_id.to_owned().into();
201 blocking(pool, move |conn| {
202 Activity::insert(conn, ap_id, &activity, local, sensitive)
208 async fn check_community_or_site_ban(
210 community_id: CommunityId,
212 ) -> Result<(), LemmyError> {
214 return Err(anyhow!("Person is banned from site").into());
216 let person_id = person.id;
218 move |conn: &'_ _| CommunityPersonBanView::get(conn, person_id, community_id).is_ok();
219 if blocking(pool, is_banned).await? {
220 return Err(anyhow!("Person is banned from community").into());
226 pub(crate) async fn send_lemmy_activity<T: Serialize>(
227 context: &LemmyContext,
230 actor: &dyn ActorType,
233 ) -> Result<(), LemmyError> {
234 if !context.settings().federation.enabled || inboxes.is_empty() {
238 info!("Sending activity {}", activity_id.to_string());
240 // Don't send anything to ourselves
241 // TODO: this should be a debug assert
242 let hostname = context.settings().get_hostname_without_port()?;
243 let inboxes: Vec<&Url> = inboxes
245 .filter(|i| i.domain().expect("valid inbox url") != hostname)
248 let serialised_activity = serde_json::to_string(&activity)?;
252 serialised_activity.clone(),
264 context.activity_queue(),