]> Untitled Git - lemmy.git/blob - crates/apub/src/http/mod.rs
Upgrading deps (#1995)
[lemmy.git] / crates / apub / src / http / mod.rs
1 use crate::{
2   activity_lists::SharedInboxActivities,
3   check_is_apub_id_valid,
4   context::WithContext,
5   fetcher::user_or_community::UserOrCommunity,
6   http::{community::receive_group_inbox, person::receive_person_inbox},
7   insert_activity,
8 };
9 use actix_web::{
10   web,
11   web::{Bytes, BytesMut, Payload},
12   HttpRequest,
13   HttpResponse,
14 };
15 use anyhow::Context;
16 use futures::StreamExt;
17 use http::StatusCode;
18 use lemmy_api_common::blocking;
19 use lemmy_apub_lib::{
20   data::Data,
21   object_id::ObjectId,
22   signatures::verify_signature,
23   traits::{ActivityHandler, ActorType},
24   APUB_JSON_CONTENT_TYPE,
25 };
26 use lemmy_db_schema::source::activity::Activity;
27 use lemmy_utils::{location_info, LemmyError};
28 use lemmy_websocket::LemmyContext;
29 use serde::{Deserialize, Serialize};
30 use std::{fmt::Debug, io::Read};
31 use tracing::info;
32 use url::Url;
33
34 mod comment;
35 mod community;
36 mod person;
37 mod post;
38 pub mod routes;
39
40 #[tracing::instrument(skip_all)]
41 pub async fn shared_inbox(
42   request: HttpRequest,
43   payload: Payload,
44   context: web::Data<LemmyContext>,
45 ) -> Result<HttpResponse, LemmyError> {
46   let unparsed = payload_to_string(payload).await?;
47   info!("Received shared inbox activity {}", unparsed);
48   let activity_data: ActivityCommonFields = serde_json::from_str(&unparsed)?;
49   let activity = serde_json::from_str::<WithContext<SharedInboxActivities>>(&unparsed)?;
50   match activity.inner() {
51     SharedInboxActivities::GroupInboxActivities(g) => {
52       receive_group_inbox(*g, activity_data, request, &context).await
53     }
54     SharedInboxActivities::PersonInboxActivities(p) => {
55       receive_person_inbox(*p, activity_data, request, &context).await
56     }
57   }
58 }
59
60 async fn payload_to_string(mut payload: Payload) -> Result<String, LemmyError> {
61   let mut bytes = BytesMut::new();
62   while let Some(item) = payload.next().await {
63     bytes.extend_from_slice(&item?);
64   }
65   let mut unparsed = String::new();
66   Bytes::from(bytes).as_ref().read_to_string(&mut unparsed)?;
67   Ok(unparsed)
68 }
69
70 #[derive(Clone, Debug, Deserialize, Serialize)]
71 #[serde(rename_all = "camelCase")]
72 pub(crate) struct ActivityCommonFields {
73   pub(crate) id: Url,
74   pub(crate) actor: Url,
75 }
76
77 // TODO: move most of this code to library
78 #[tracing::instrument(skip_all)]
79 async fn receive_activity<'a, T>(
80   request: HttpRequest,
81   activity: T,
82   activity_data: ActivityCommonFields,
83   context: &LemmyContext,
84 ) -> Result<HttpResponse, LemmyError>
85 where
86   T: ActivityHandler<DataType = LemmyContext>
87     + Clone
88     + Deserialize<'a>
89     + Serialize
90     + std::fmt::Debug
91     + Send
92     + 'static,
93 {
94   check_is_apub_id_valid(&activity_data.actor, false, &context.settings())?;
95   let request_counter = &mut 0;
96   let actor = ObjectId::<UserOrCommunity>::new(activity_data.actor)
97     .dereference(context, context.client(), request_counter)
98     .await?;
99   verify_signature(&request, &actor.public_key())?;
100
101   info!("Verifying activity {}", activity_data.id.to_string());
102   activity
103     .verify(&Data::new(context.clone()), request_counter)
104     .await?;
105   assert_activity_not_local(&activity_data.id, &context.settings().hostname)?;
106
107   // Log the activity, so we avoid receiving and parsing it twice. Note that this could still happen
108   // if we receive the same activity twice in very quick succession.
109   let object_value = serde_json::to_value(&activity)?;
110   insert_activity(&activity_data.id, object_value, false, true, context.pool()).await?;
111
112   info!("Receiving activity {}", activity_data.id.to_string());
113   activity
114     .receive(&Data::new(context.clone()), request_counter)
115     .await?;
116   Ok(HttpResponse::Ok().finish())
117 }
118
119 /// Convert the data to json and turn it into an HTTP Response with the correct ActivityPub
120 /// headers.
121 fn create_apub_response<T>(data: &T) -> HttpResponse
122 where
123   T: Serialize,
124 {
125   HttpResponse::Ok()
126     .content_type(APUB_JSON_CONTENT_TYPE)
127     .json(WithContext::new(data))
128 }
129
130 fn create_json_apub_response(data: serde_json::Value) -> HttpResponse {
131   HttpResponse::Ok()
132     .content_type(APUB_JSON_CONTENT_TYPE)
133     .json(data)
134 }
135
136 fn create_apub_tombstone_response<T>(data: &T) -> HttpResponse
137 where
138   T: Serialize,
139 {
140   HttpResponse::Gone()
141     .content_type(APUB_JSON_CONTENT_TYPE)
142     .status(StatusCode::GONE)
143     .json(WithContext::new(data))
144 }
145
146 #[derive(Deserialize)]
147 pub struct ActivityQuery {
148   type_: String,
149   id: String,
150 }
151
152 /// Return the ActivityPub json representation of a local activity over HTTP.
153 #[tracing::instrument(skip_all)]
154 pub(crate) async fn get_activity(
155   info: web::Path<ActivityQuery>,
156   context: web::Data<LemmyContext>,
157 ) -> Result<HttpResponse, LemmyError> {
158   let settings = context.settings();
159   let activity_id = Url::parse(&format!(
160     "{}/activities/{}/{}",
161     settings.get_protocol_and_hostname(),
162     info.type_,
163     info.id
164   ))?
165   .into();
166   let activity = blocking(context.pool(), move |conn| {
167     Activity::read_from_apub_id(conn, &activity_id)
168   })
169   .await??;
170
171   let sensitive = activity.sensitive.unwrap_or(true);
172   if !activity.local || sensitive {
173     Ok(HttpResponse::NotFound().finish())
174   } else {
175     Ok(create_json_apub_response(activity.data))
176   }
177 }
178
179 fn assert_activity_not_local(id: &Url, hostname: &str) -> Result<(), LemmyError> {
180   let activity_domain = id.domain().context(location_info!())?;
181
182   if activity_domain == hostname {
183     let error = LemmyError::from(anyhow::anyhow!(
184       "Error: received activity which was sent by local instance: {:?}",
185       id
186     ));
187     return Err(error.with_message("received_local_activity"));
188   }
189   Ok(())
190 }