2 extern crate lazy_static;
5 pub mod activity_queue;
12 use crate::{extensions::signatures::PublicKey, fetcher::post_or_comment::PostOrComment};
13 use anyhow::{anyhow, Context};
14 use lemmy_api_common::blocking;
15 use lemmy_db_queries::{source::activity::Activity_, DbPool};
16 use lemmy_db_schema::{
17 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};
25 use url::{ParseError, Url};
27 static APUB_JSON_CONTENT_TYPE: &str = "application/activity+json";
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 /// Common methods provided by ActivityPub actors (community and person). Not all methods are
96 /// implemented by all actors.
98 fn is_local(&self) -> bool;
99 fn actor_id(&self) -> Url;
100 fn name(&self) -> String;
102 // TODO: every actor should have a public key, so this shouldnt be an option (needs to be fixed in db)
103 fn public_key(&self) -> Option<String>;
104 fn private_key(&self) -> Option<String>;
106 fn get_shared_inbox_or_inbox_url(&self) -> Url;
108 /// Outbox URL is not generally used by Lemmy, so it can be generated on the fly (but only for
110 fn get_outbox_url(&self) -> Result<Url, LemmyError> {
112 if !self.is_local() {
113 return Err(anyhow!("get_outbox_url() called for remote actor").into());
116 Ok(Url::parse(&format!("{}/outbox", &self.actor_id()))?)
119 fn get_public_key(&self) -> Result<PublicKey, LemmyError> {
121 id: format!("{}#main-key", self.actor_id()),
122 owner: self.actor_id(),
123 public_key_pem: self.public_key().context(location_info!())?,
128 #[async_trait::async_trait(?Send)]
129 pub trait CommunityType {
130 fn followers_url(&self) -> Url;
131 async fn get_follower_inboxes(
135 ) -> Result<Vec<Url>, LemmyError>;
138 pub enum EndpointType {
146 /// Generates an apub endpoint for a given domain, IE xyz.tld
147 fn generate_apub_endpoint_for_domain(
148 endpoint_type: EndpointType,
151 ) -> Result<DbUrl, ParseError> {
152 let point = match endpoint_type {
153 EndpointType::Community => "c",
154 EndpointType::Person => "u",
155 EndpointType::Post => "post",
156 EndpointType::Comment => "comment",
157 EndpointType::PrivateMessage => "private_message",
160 Ok(Url::parse(&format!("{}/{}/{}", domain, point, name))?.into())
163 /// Generates the ActivityPub ID for a given object type and ID.
164 pub fn generate_apub_endpoint(
165 endpoint_type: EndpointType,
167 protocol_and_hostname: &str,
168 ) -> Result<DbUrl, ParseError> {
169 generate_apub_endpoint_for_domain(endpoint_type, name, protocol_and_hostname)
172 pub fn generate_followers_url(actor_id: &DbUrl) -> Result<DbUrl, ParseError> {
173 Ok(Url::parse(&format!("{}/followers", actor_id))?.into())
176 pub fn generate_inbox_url(actor_id: &DbUrl) -> Result<DbUrl, ParseError> {
177 Ok(Url::parse(&format!("{}/inbox", actor_id))?.into())
180 pub fn generate_shared_inbox_url(actor_id: &DbUrl) -> Result<DbUrl, LemmyError> {
181 let actor_id: Url = actor_id.clone().into();
185 &actor_id.host_str().context(location_info!())?,
186 if let Some(port) = actor_id.port() {
192 Ok(Url::parse(&url)?.into())
195 fn generate_moderators_url(community_id: &DbUrl) -> Result<DbUrl, LemmyError> {
196 Ok(Url::parse(&format!("{}/moderators", community_id))?.into())
199 /// Takes in a shortname of the type dessalines@xyz.tld or dessalines (assumed to be local), and outputs the actor id.
200 /// Used in the API for communities and users.
201 pub fn build_actor_id_from_shortname(
202 endpoint_type: EndpointType,
205 ) -> Result<DbUrl, ParseError> {
206 let split = short_name.split('@').collect::<Vec<&str>>();
210 // If there's no @, its local
211 let domain = if split.len() == 1 {
212 settings.get_protocol_and_hostname()
214 format!("{}://{}", settings.get_protocol_string(), split[1])
217 generate_apub_endpoint_for_domain(endpoint_type, name, &domain)
220 /// Store a sent or received activity in the database, for logging purposes. These records are not
222 async fn insert_activity<T>(
228 ) -> Result<(), LemmyError>
230 T: Serialize + std::fmt::Debug + Send + 'static,
232 let ap_id = ap_id.to_owned().into();
233 blocking(pool, move |conn| {
234 Activity::insert(conn, ap_id, &activity, local, sensitive)
240 async fn check_community_or_site_ban(
242 community_id: CommunityId,
244 ) -> Result<(), LemmyError> {
246 return Err(anyhow!("Person is banned from site").into());
248 let person_id = person.id;
250 move |conn: &'_ _| CommunityPersonBanView::get(conn, person_id, community_id).is_ok();
251 if blocking(pool, is_banned).await? {
252 return Err(anyhow!("Person is banned from community").into());