2 extern crate lazy_static;
5 pub mod activity_queue;
12 use crate::extensions::signatures::PublicKey;
13 use anyhow::{anyhow, Context};
15 use lemmy_api_common::blocking;
16 use lemmy_db_queries::{source::activity::Activity_, ApubObject, DbPool};
17 use lemmy_db_schema::{
22 person::{Person as DbPerson, Person},
24 private_message::PrivateMessage,
29 use lemmy_db_views_actor::community_person_ban_view::CommunityPersonBanView;
30 use lemmy_utils::{location_info, settings::structs::Settings, LemmyError};
31 use lemmy_websocket::LemmyContext;
34 use url::{ParseError, Url};
36 static APUB_JSON_CONTENT_TYPE: &str = "application/activity+json";
38 /// Checks if the ID is allowed for sending or receiving.
40 /// In particular, it checks for:
41 /// - federation being enabled (if its disabled, only local URLs are allowed)
42 /// - the correct scheme (either http or https)
43 /// - URL being in the allowlist (if it is active)
44 /// - URL not being in the blocklist (if it is active)
46 pub(crate) fn check_is_apub_id_valid(
48 use_strict_allowlist: bool,
49 ) -> Result<(), LemmyError> {
50 let settings = Settings::get();
51 let domain = apub_id.domain().context(location_info!())?.to_string();
52 let local_instance = settings.get_hostname_without_port()?;
54 if !settings.federation.enabled {
55 return if domain == local_instance {
60 "Trying to connect with {}, but federation is disabled",
68 let host = apub_id.host_str().context(location_info!())?;
69 let host_as_ip = host.parse::<IpAddr>();
70 if host == "localhost" || host_as_ip.is_ok() {
71 return Err(anyhow!("invalid hostname {}: {}", host, apub_id).into());
74 if apub_id.scheme() != Settings::get().get_protocol_string() {
75 return Err(anyhow!("invalid apub id scheme {}: {}", apub_id.scheme(), apub_id).into());
78 // TODO: might be good to put the part above in one method, and below in another
79 // (which only gets called in apub::objects)
80 // -> no that doesnt make sense, we still need the code below for blocklist and strict allowlist
81 if let Some(blocked) = Settings::get().federation.blocked_instances {
82 if blocked.contains(&domain) {
83 return Err(anyhow!("{} is in federation blocklist", domain).into());
87 if let Some(mut allowed) = Settings::get().federation.allowed_instances {
88 // Only check allowlist if this is a community, or strict allowlist is enabled.
89 let strict_allowlist = Settings::get().federation.strict_allowlist;
90 if use_strict_allowlist || strict_allowlist {
91 // need to allow this explicitly because apub receive might contain objects from our local
93 allowed.push(local_instance);
95 if !allowed.contains(&domain) {
96 return Err(anyhow!("{} not in federation allowlist", domain).into());
104 /// Common methods provided by ActivityPub actors (community and person). Not all methods are
105 /// implemented by all actors.
107 fn is_local(&self) -> bool;
108 fn actor_id(&self) -> Url;
109 fn name(&self) -> String;
111 // TODO: every actor should have a public key, so this shouldnt be an option (needs to be fixed in db)
112 fn public_key(&self) -> Option<String>;
113 fn private_key(&self) -> Option<String>;
115 fn get_shared_inbox_or_inbox_url(&self) -> Url;
117 /// Outbox URL is not generally used by Lemmy, so it can be generated on the fly (but only for
119 fn get_outbox_url(&self) -> Result<Url, LemmyError> {
121 if !self.is_local() {
122 return Err(anyhow!("get_outbox_url() called for remote actor").into());
125 Ok(Url::parse(&format!("{}/outbox", &self.actor_id()))?)
128 fn get_public_key(&self) -> Result<PublicKey, LemmyError> {
130 id: format!("{}#main-key", self.actor_id()),
131 owner: self.actor_id(),
132 public_key_pem: self.public_key().context(location_info!())?,
137 #[async_trait::async_trait(?Send)]
138 pub trait CommunityType {
139 fn followers_url(&self) -> Url;
140 async fn get_follower_inboxes(&self, pool: &DbPool) -> Result<Vec<Url>, LemmyError>;
143 pub enum EndpointType {
151 /// Generates an apub endpoint for a given domain, IE xyz.tld
152 fn generate_apub_endpoint_for_domain(
153 endpoint_type: EndpointType,
156 ) -> Result<DbUrl, ParseError> {
157 let point = match endpoint_type {
158 EndpointType::Community => "c",
159 EndpointType::Person => "u",
160 EndpointType::Post => "post",
161 EndpointType::Comment => "comment",
162 EndpointType::PrivateMessage => "private_message",
165 Ok(Url::parse(&format!("{}/{}/{}", domain, point, name))?.into())
168 /// Generates the ActivityPub ID for a given object type and ID.
169 pub fn generate_apub_endpoint(
170 endpoint_type: EndpointType,
172 ) -> Result<DbUrl, ParseError> {
173 generate_apub_endpoint_for_domain(
176 &Settings::get().get_protocol_and_hostname(),
180 pub fn generate_followers_url(actor_id: &DbUrl) -> Result<DbUrl, ParseError> {
181 Ok(Url::parse(&format!("{}/followers", actor_id))?.into())
184 pub fn generate_inbox_url(actor_id: &DbUrl) -> Result<DbUrl, ParseError> {
185 Ok(Url::parse(&format!("{}/inbox", actor_id))?.into())
188 pub fn generate_shared_inbox_url(actor_id: &DbUrl) -> Result<DbUrl, LemmyError> {
189 let actor_id: Url = actor_id.clone().into();
193 &actor_id.host_str().context(location_info!())?,
194 if let Some(port) = actor_id.port() {
200 Ok(Url::parse(&url)?.into())
203 fn generate_moderators_url(community_id: &DbUrl) -> Result<DbUrl, LemmyError> {
204 Ok(Url::parse(&format!("{}/moderators", community_id))?.into())
207 /// Takes in a shortname of the type dessalines@xyz.tld or dessalines (assumed to be local), and outputs the actor id.
208 /// Used in the API for communities and users.
209 pub fn build_actor_id_from_shortname(
210 endpoint_type: EndpointType,
212 ) -> Result<DbUrl, ParseError> {
213 let split = short_name.split('@').collect::<Vec<&str>>();
217 // If there's no @, its local
218 let domain = if split.len() == 1 {
219 Settings::get().get_protocol_and_hostname()
221 format!("{}://{}", Settings::get().get_protocol_string(), split[1])
224 generate_apub_endpoint_for_domain(endpoint_type, name, &domain)
227 /// Store a sent or received activity in the database, for logging purposes. These records are not
229 async fn insert_activity<T>(
235 ) -> Result<(), LemmyError>
237 T: Serialize + std::fmt::Debug + Send + 'static,
239 let ap_id = ap_id.to_owned().into();
240 blocking(pool, move |conn| {
241 Activity::insert(conn, ap_id, &activity, local, sensitive)
247 pub enum PostOrComment {
248 Comment(Box<Comment>),
253 pub(crate) fn ap_id(&self) -> Url {
255 PostOrComment::Post(p) => p.ap_id.clone(),
256 PostOrComment::Comment(c) => c.ap_id.clone(),
262 /// Tries to find a post or comment in the local database, without any network requests.
263 /// This is used to handle deletions and removals, because in case we dont have the object, we can
264 /// simply ignore the activity.
265 pub(crate) async fn find_post_or_comment_by_id(
266 context: &LemmyContext,
268 ) -> Result<PostOrComment, LemmyError> {
269 let ap_id = apub_id.clone();
270 let post = blocking(context.pool(), move |conn| {
271 Post::read_from_apub_id(conn, &ap_id.into())
274 if let Ok(p) = post {
275 return Ok(PostOrComment::Post(Box::new(p)));
278 let ap_id = apub_id.clone();
279 let comment = blocking(context.pool(), move |conn| {
280 Comment::read_from_apub_id(conn, &ap_id.into())
283 if let Ok(c) = comment {
284 return Ok(PostOrComment::Comment(Box::new(c)));
292 Comment(Box<Comment>),
294 Community(Box<Community>),
295 Person(Box<DbPerson>),
296 PrivateMessage(Box<PrivateMessage>),
299 async fn find_object_by_id(context: &LemmyContext, apub_id: Url) -> Result<Object, LemmyError> {
300 let ap_id = apub_id.clone();
301 if let Ok(pc) = find_post_or_comment_by_id(context, ap_id.to_owned()).await {
303 PostOrComment::Post(p) => Object::Post(Box::new(*p)),
304 PostOrComment::Comment(c) => Object::Comment(Box::new(*c)),
308 let ap_id = apub_id.clone();
309 let person = blocking(context.pool(), move |conn| {
310 DbPerson::read_from_apub_id(conn, &ap_id.into())
313 if let Ok(u) = person {
314 return Ok(Object::Person(Box::new(u)));
317 let ap_id = apub_id.clone();
318 let community = blocking(context.pool(), move |conn| {
319 Community::read_from_apub_id(conn, &ap_id.into())
322 if let Ok(c) = community {
323 return Ok(Object::Community(Box::new(c)));
326 let private_message = blocking(context.pool(), move |conn| {
327 PrivateMessage::read_from_apub_id(conn, &apub_id.into())
330 if let Ok(pm) = private_message {
331 return Ok(Object::PrivateMessage(Box::new(pm)));
337 async fn check_community_or_site_ban(
339 community_id: CommunityId,
341 ) -> Result<(), LemmyError> {
343 return Err(anyhow!("Person is banned from site").into());
345 let person_id = person.id;
347 move |conn: &'_ _| CommunityPersonBanView::get(conn, person_id, community_id).is_ok();
348 if blocking(pool, is_banned).await? {
349 return Err(anyhow!("Person is banned from community").into());