]> Untitled Git - lemmy.git/blob - crates/apub/src/http/mod.rs
Improved error message when attempting to fetch non-local object (fixes #2715) (...
[lemmy.git] / crates / apub / src / http / mod.rs
1 use crate::{
2   activity_lists::SharedInboxActivities,
3   fetcher::user_or_community::UserOrCommunity,
4   insert_activity,
5   local_instance,
6   protocol::objects::tombstone::Tombstone,
7   CONTEXT,
8 };
9 use activitypub_federation::{
10   core::inbox::receive_activity,
11   data::Data,
12   deser::context::WithContext,
13   traits::{ActivityHandler, Actor, ApubObject},
14   APUB_JSON_CONTENT_TYPE,
15 };
16 use actix_web::{web, HttpRequest, HttpResponse};
17 use http::StatusCode;
18 use lemmy_api_common::context::LemmyContext;
19 use lemmy_db_schema::source::activity::Activity;
20 use lemmy_utils::error::LemmyError;
21 use once_cell::sync::OnceCell;
22 use serde::{de::DeserializeOwned, Deserialize, Serialize};
23 use serde_json::Value;
24 use std::ops::Deref;
25 use tracing::{debug, log::info};
26 use url::Url;
27
28 mod comment;
29 mod community;
30 mod person;
31 mod post;
32 pub mod routes;
33 pub mod site;
34
35 pub async fn shared_inbox(
36   request: HttpRequest,
37   payload: String,
38   context: web::Data<LemmyContext>,
39 ) -> Result<HttpResponse, LemmyError> {
40   receive_lemmy_activity::<SharedInboxActivities, UserOrCommunity>(request, payload, context).await
41 }
42
43 pub async fn receive_lemmy_activity<Activity, ActorT>(
44   request: HttpRequest,
45   payload: String,
46   context: web::Data<LemmyContext>,
47 ) -> Result<HttpResponse, LemmyError>
48 where
49   Activity: ActivityHandler<DataType = LemmyContext, Error = LemmyError>
50     + DeserializeOwned
51     + Send
52     + 'static,
53   ActorT: ApubObject<DataType = LemmyContext, Error = LemmyError> + Actor + Send + 'static,
54   for<'de2> <ActorT as ApubObject>::ApubType: serde::Deserialize<'de2>,
55 {
56   static DATA: OnceCell<Data<LemmyContext>> = OnceCell::new();
57   let activity_value: Value = serde_json::from_str(&payload)?;
58   debug!("Parsing activity {}", payload);
59   let activity: Activity = serde_json::from_value(activity_value.clone())?;
60   // Log the activity, so we avoid receiving and parsing it twice.
61   let insert = insert_activity(activity.id(), activity_value, false, true, context.pool()).await?;
62   if !insert {
63     debug!("Received duplicate activity {}", activity.id().to_string());
64     return Ok(HttpResponse::BadRequest().finish());
65   }
66   info!("Received activity {}", payload);
67
68   let data = DATA.get_or_init(|| Data::new(context.get_ref().clone()));
69   receive_activity::<Activity, ActorT, LemmyContext>(
70     request,
71     activity,
72     local_instance(&context).await,
73     data,
74   )
75   .await
76 }
77
78 /// Convert the data to json and turn it into an HTTP Response with the correct ActivityPub
79 /// headers.
80 fn create_apub_response<T>(data: &T) -> HttpResponse
81 where
82   T: Serialize,
83 {
84   HttpResponse::Ok()
85     .content_type(APUB_JSON_CONTENT_TYPE)
86     .json(WithContext::new(data, CONTEXT.deref().clone()))
87 }
88
89 fn create_json_apub_response(data: serde_json::Value) -> HttpResponse {
90   HttpResponse::Ok()
91     .content_type(APUB_JSON_CONTENT_TYPE)
92     .json(data)
93 }
94
95 fn create_apub_tombstone_response<T: Into<Url>>(id: T) -> HttpResponse {
96   let tombstone = Tombstone::new(id.into());
97   HttpResponse::Gone()
98     .content_type(APUB_JSON_CONTENT_TYPE)
99     .status(StatusCode::GONE)
100     .json(WithContext::new(tombstone, CONTEXT.deref().clone()))
101 }
102
103 fn err_object_not_local() -> LemmyError {
104   LemmyError::from_message("Object not local, fetch it from original instance")
105 }
106
107 #[derive(Deserialize)]
108 pub struct ActivityQuery {
109   type_: String,
110   id: String,
111 }
112
113 /// Return the ActivityPub json representation of a local activity over HTTP.
114 #[tracing::instrument(skip_all)]
115 pub(crate) async fn get_activity(
116   info: web::Path<ActivityQuery>,
117   context: web::Data<LemmyContext>,
118 ) -> Result<HttpResponse, LemmyError> {
119   let settings = context.settings();
120   let activity_id = Url::parse(&format!(
121     "{}/activities/{}/{}",
122     settings.get_protocol_and_hostname(),
123     info.type_,
124     info.id
125   ))?
126   .into();
127   let activity = Activity::read_from_apub_id(context.pool(), &activity_id).await?;
128
129   let sensitive = activity.sensitive.unwrap_or(true);
130   if !activity.local {
131     return Err(err_object_not_local());
132   } else if sensitive {
133     Ok(HttpResponse::Forbidden().finish())
134   } else {
135     Ok(create_json_apub_response(activity.data))
136   }
137 }