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_schema::{
13 newtypes::{CommunityId, DbUrl},
14 source::{activity::Activity, person::Person},
17 use lemmy_db_views_actor::community_person_ban_view::CommunityPersonBanView;
18 use lemmy_utils::{location_info, settings::structs::Settings, LemmyError};
19 use lemmy_websocket::LemmyContext;
23 use url::{ParseError, Url};
25 /// Checks if the ID is allowed for sending or receiving.
27 /// In particular, it checks for:
28 /// - federation being enabled (if its disabled, only local URLs are allowed)
29 /// - the correct scheme (either http or https)
30 /// - URL being in the allowlist (if it is active)
31 /// - URL not being in the blocklist (if it is active)
33 pub(crate) fn check_is_apub_id_valid(
35 use_strict_allowlist: bool,
37 ) -> Result<(), LemmyError> {
38 let domain = apub_id.domain().context(location_info!())?.to_string();
39 let local_instance = settings.get_hostname_without_port()?;
41 if !settings.federation.enabled {
42 return if domain == local_instance {
47 "Trying to connect with {}, but federation is disabled",
55 let host = apub_id.host_str().context(location_info!())?;
56 let host_as_ip = host.parse::<IpAddr>();
57 if host == "localhost" || host_as_ip.is_ok() {
58 return Err(anyhow!("invalid hostname {}: {}", host, apub_id).into());
61 if apub_id.scheme() != settings.get_protocol_string() {
62 return Err(anyhow!("invalid apub id scheme {}: {}", apub_id.scheme(), apub_id).into());
65 // TODO: might be good to put the part above in one method, and below in another
66 // (which only gets called in apub::objects)
67 // -> no that doesnt make sense, we still need the code below for blocklist and strict allowlist
68 if let Some(blocked) = settings.to_owned().federation.blocked_instances {
69 if blocked.contains(&domain) {
70 return Err(anyhow!("{} is in federation blocklist", domain).into());
74 if let Some(mut allowed) = settings.to_owned().federation.allowed_instances {
75 // Only check allowlist if this is a community, or strict allowlist is enabled.
76 let strict_allowlist = settings.to_owned().federation.strict_allowlist;
77 if use_strict_allowlist || strict_allowlist {
78 // need to allow this explicitly because apub receive might contain objects from our local
80 allowed.push(local_instance);
82 if !allowed.contains(&domain) {
83 return Err(anyhow!("{} not in federation allowlist", domain).into());
91 #[async_trait::async_trait(?Send)]
92 pub trait CommunityType {
93 fn followers_url(&self) -> Url;
94 async fn get_follower_inboxes(
98 ) -> Result<Vec<Url>, LemmyError>;
101 pub enum EndpointType {
109 /// Generates an apub endpoint for a given domain, IE xyz.tld
110 fn generate_apub_endpoint_for_domain(
111 endpoint_type: EndpointType,
114 ) -> Result<DbUrl, ParseError> {
115 let point = match endpoint_type {
116 EndpointType::Community => "c",
117 EndpointType::Person => "u",
118 EndpointType::Post => "post",
119 EndpointType::Comment => "comment",
120 EndpointType::PrivateMessage => "private_message",
123 Ok(Url::parse(&format!("{}/{}/{}", domain, point, name))?.into())
126 /// Generates the ActivityPub ID for a given object type and ID.
127 pub fn generate_apub_endpoint(
128 endpoint_type: EndpointType,
130 protocol_and_hostname: &str,
131 ) -> Result<DbUrl, ParseError> {
132 generate_apub_endpoint_for_domain(endpoint_type, name, protocol_and_hostname)
135 pub fn generate_followers_url(actor_id: &DbUrl) -> Result<DbUrl, ParseError> {
136 Ok(Url::parse(&format!("{}/followers", actor_id))?.into())
139 pub fn generate_inbox_url(actor_id: &DbUrl) -> Result<DbUrl, ParseError> {
140 Ok(Url::parse(&format!("{}/inbox", actor_id))?.into())
143 pub fn generate_shared_inbox_url(actor_id: &DbUrl) -> Result<DbUrl, LemmyError> {
144 let actor_id: Url = actor_id.clone().into();
148 &actor_id.host_str().context(location_info!())?,
149 if let Some(port) = actor_id.port() {
155 Ok(Url::parse(&url)?.into())
158 pub fn generate_outbox_url(actor_id: &DbUrl) -> Result<DbUrl, ParseError> {
159 Ok(Url::parse(&format!("{}/outbox", actor_id))?.into())
162 fn generate_moderators_url(community_id: &DbUrl) -> Result<DbUrl, LemmyError> {
163 Ok(Url::parse(&format!("{}/moderators", community_id))?.into())
166 /// Takes in a shortname of the type dessalines@xyz.tld or dessalines (assumed to be local), and outputs the actor id.
167 /// Used in the API for communities and users.
168 pub fn build_actor_id_from_shortname(
169 endpoint_type: EndpointType,
172 ) -> Result<DbUrl, ParseError> {
173 let split = short_name.split('@').collect::<Vec<&str>>();
177 // If there's no @, its local
178 let domain = if split.len() == 1 {
179 settings.get_protocol_and_hostname()
181 format!("{}://{}", settings.get_protocol_string(), split[1])
184 generate_apub_endpoint_for_domain(endpoint_type, name, &domain)
187 /// Store a sent or received activity in the database, for logging purposes. These records are not
189 async fn insert_activity<T>(
195 ) -> Result<(), LemmyError>
197 T: Serialize + std::fmt::Debug + Send + 'static,
199 let ap_id = ap_id.to_owned().into();
200 blocking(pool, move |conn| {
201 Activity::insert(conn, ap_id, &activity, local, sensitive)
207 async fn check_community_or_site_ban(
209 community_id: CommunityId,
211 ) -> Result<(), LemmyError> {
213 return Err(anyhow!("Person is banned from site").into());
215 let person_id = person.id;
217 move |conn: &'_ _| CommunityPersonBanView::get(conn, person_id, community_id).is_ok();
218 if blocking(pool, is_banned).await? {
219 return Err(anyhow!("Person is banned from community").into());
225 pub(crate) async fn send_lemmy_activity<T: Serialize>(
226 context: &LemmyContext,
229 actor: &dyn ActorType,
232 ) -> Result<(), LemmyError> {
233 if !context.settings().federation.enabled || inboxes.is_empty() {
237 info!("Sending activity {}", activity_id.to_string());
239 // Don't send anything to ourselves
240 // TODO: this should be a debug assert
241 let hostname = context.settings().get_hostname_without_port()?;
242 let inboxes: Vec<&Url> = inboxes
244 .filter(|i| i.domain().expect("valid inbox url") != hostname)
247 let serialised_activity = serde_json::to_string(&activity)?;
251 serialised_activity.clone(),
263 context.activity_queue(),