]> Untitled Git - lemmy.git/blob - crates/apub/src/activities/mod.rs
Add person name to PersonIsBannedFromSite error (#3786) (#3855)
[lemmy.git] / crates / apub / src / activities / mod.rs
1 use self::following::send_follow_community;
2 use crate::{
3   activities::{
4     block::{send_ban_from_community, send_ban_from_site},
5     community::{
6       collection_add::{send_add_mod_to_community, send_feature_post},
7       lock_page::send_lock_post,
8       update::send_update_community,
9     },
10     create_or_update::private_message::send_create_or_update_pm,
11     deletion::{
12       delete_user::delete_user,
13       send_apub_delete_in_community,
14       send_apub_delete_in_community_new,
15       send_apub_delete_private_message,
16       DeletableObjects,
17     },
18     voting::send_like_activity,
19   },
20   objects::{community::ApubCommunity, person::ApubPerson},
21   protocol::activities::{
22     community::report::Report,
23     create_or_update::{note::CreateOrUpdateNote, page::CreateOrUpdatePage},
24     CreateOrUpdateType,
25   },
26   CONTEXT,
27 };
28 use activitypub_federation::{
29   activity_queue::send_activity,
30   config::Data,
31   fetch::object_id::ObjectId,
32   kinds::public,
33   protocol::context::WithContext,
34   traits::{ActivityHandler, Actor},
35 };
36 use anyhow::anyhow;
37 use lemmy_api_common::{
38   context::LemmyContext,
39   send_activity::{ActivityChannel, SendActivityData},
40 };
41 use lemmy_db_schema::{
42   newtypes::CommunityId,
43   source::{
44     activity::{SentActivity, SentActivityForm},
45     community::Community,
46     instance::Instance,
47   },
48 };
49 use lemmy_db_views_actor::structs::{CommunityPersonBanView, CommunityView};
50 use lemmy_utils::{
51   error::{LemmyError, LemmyErrorExt, LemmyErrorType, LemmyResult},
52   spawn_try_task,
53   SYNCHRONOUS_FEDERATION,
54 };
55 use moka::future::Cache;
56 use once_cell::sync::Lazy;
57 use serde::Serialize;
58 use std::{ops::Deref, sync::Arc, time::Duration};
59 use tracing::info;
60 use url::{ParseError, Url};
61 use uuid::Uuid;
62
63 pub mod block;
64 pub mod community;
65 pub mod create_or_update;
66 pub mod deletion;
67 pub mod following;
68 pub mod unfederated;
69 pub mod voting;
70
71 /// Amount of time that the list of dead instances is cached. This is only updated once a day,
72 /// so there is no harm in caching it for a longer time.
73 pub static DEAD_INSTANCE_LIST_CACHE_DURATION: Duration = Duration::from_secs(30 * 60);
74
75 /// Checks that the specified Url actually identifies a Person (by fetching it), and that the person
76 /// doesn't have a site ban.
77 #[tracing::instrument(skip_all)]
78 async fn verify_person(
79   person_id: &ObjectId<ApubPerson>,
80   context: &Data<LemmyContext>,
81 ) -> Result<(), LemmyError> {
82   let person = person_id.dereference(context).await?;
83   if person.banned {
84     return Err(anyhow!("Person {} is banned", person_id))
85       .with_lemmy_type(LemmyErrorType::CouldntUpdateComment);
86   }
87   Ok(())
88 }
89
90 /// Fetches the person and community to verify their type, then checks if person is banned from site
91 /// or community.
92 #[tracing::instrument(skip_all)]
93 pub(crate) async fn verify_person_in_community(
94   person_id: &ObjectId<ApubPerson>,
95   community: &ApubCommunity,
96   context: &Data<LemmyContext>,
97 ) -> Result<(), LemmyError> {
98   let person = person_id.dereference(context).await?;
99   if person.banned {
100     return Err(LemmyErrorType::PersonIsBannedFromSite(
101       person.actor_id.to_string(),
102     ))?;
103   }
104   let person_id = person.id;
105   let community_id = community.id;
106   let is_banned = CommunityPersonBanView::get(&mut context.pool(), person_id, community_id)
107     .await
108     .is_ok();
109   if is_banned {
110     return Err(LemmyErrorType::PersonIsBannedFromCommunity)?;
111   }
112
113   Ok(())
114 }
115
116 /// Verify that mod action in community was performed by a moderator.
117 ///
118 /// * `mod_id` - Activitypub ID of the mod or admin who performed the action
119 /// * `object_id` - Activitypub ID of the actor or object that is being moderated
120 /// * `community` - The community inside which moderation is happening
121 #[tracing::instrument(skip_all)]
122 pub(crate) async fn verify_mod_action(
123   mod_id: &ObjectId<ApubPerson>,
124   object_id: &Url,
125   community_id: CommunityId,
126   context: &Data<LemmyContext>,
127 ) -> Result<(), LemmyError> {
128   let mod_ = mod_id.dereference(context).await?;
129
130   let is_mod_or_admin =
131     CommunityView::is_mod_or_admin(&mut context.pool(), mod_.id, community_id).await?;
132   if is_mod_or_admin {
133     return Ok(());
134   }
135
136   // mod action comes from the same instance as the moderated object, so it was presumably done
137   // by an instance admin.
138   // TODO: federate instance admin status and check it here
139   if mod_id.inner().domain() == object_id.domain() {
140     return Ok(());
141   }
142
143   Err(LemmyErrorType::NotAModerator)?
144 }
145
146 pub(crate) fn verify_is_public(to: &[Url], cc: &[Url]) -> Result<(), LemmyError> {
147   if ![to, cc].iter().any(|set| set.contains(&public())) {
148     Err(LemmyErrorType::ObjectIsNotPublic)?;
149   }
150   Ok(())
151 }
152
153 pub(crate) fn verify_community_matches<T>(
154   a: &ObjectId<ApubCommunity>,
155   b: T,
156 ) -> Result<(), LemmyError>
157 where
158   T: Into<ObjectId<ApubCommunity>>,
159 {
160   let b: ObjectId<ApubCommunity> = b.into();
161   if a != &b {
162     Err(LemmyErrorType::InvalidCommunity)?;
163   }
164   Ok(())
165 }
166
167 pub(crate) fn check_community_deleted_or_removed(community: &Community) -> Result<(), LemmyError> {
168   if community.deleted || community.removed {
169     Err(LemmyErrorType::CannotCreatePostOrCommentInDeletedOrRemovedCommunity)?
170   } else {
171     Ok(())
172   }
173 }
174
175 /// Generate a unique ID for an activity, in the format:
176 /// `http(s)://example.com/receive/create/202daf0a-1489-45df-8d2e-c8a3173fed36`
177 fn generate_activity_id<T>(kind: T, protocol_and_hostname: &str) -> Result<Url, ParseError>
178 where
179   T: ToString,
180 {
181   let id = format!(
182     "{}/activities/{}/{}",
183     protocol_and_hostname,
184     kind.to_string().to_lowercase(),
185     Uuid::new_v4()
186   );
187   Url::parse(&id)
188 }
189
190 #[tracing::instrument(skip_all)]
191 async fn send_lemmy_activity<Activity, ActorT>(
192   data: &Data<LemmyContext>,
193   activity: Activity,
194   actor: &ActorT,
195   mut inbox: Vec<Url>,
196   sensitive: bool,
197 ) -> Result<(), LemmyError>
198 where
199   Activity: ActivityHandler + Serialize + Send + Sync + Clone,
200   ActorT: Actor,
201   Activity: ActivityHandler<Error = LemmyError>,
202 {
203   static CACHE: Lazy<Cache<(), Arc<Vec<String>>>> = Lazy::new(|| {
204     Cache::builder()
205       .max_capacity(1)
206       .time_to_live(DEAD_INSTANCE_LIST_CACHE_DURATION)
207       .build()
208   });
209   let dead_instances = CACHE
210     .try_get_with((), async {
211       Ok::<_, diesel::result::Error>(Arc::new(Instance::dead_instances(&mut data.pool()).await?))
212     })
213     .await?;
214
215   inbox.retain(|i| {
216     let domain = i.domain().expect("has domain").to_string();
217     !dead_instances.contains(&domain)
218   });
219   info!("Sending activity {}", activity.id().to_string());
220   let activity = WithContext::new(activity, CONTEXT.deref().clone());
221
222   let form = SentActivityForm {
223     ap_id: activity.id().clone().into(),
224     data: serde_json::to_value(activity.clone())?,
225     sensitive,
226   };
227   SentActivity::create(&mut data.pool(), form).await?;
228   send_activity(activity, actor, inbox, data).await?;
229
230   Ok(())
231 }
232
233 pub async fn handle_outgoing_activities(context: Data<LemmyContext>) -> LemmyResult<()> {
234   while let Some(data) = ActivityChannel::retrieve_activity().await {
235     match_outgoing_activities(data, &context.reset_request_count()).await?
236   }
237   Ok(())
238 }
239
240 pub async fn match_outgoing_activities(
241   data: SendActivityData,
242   context: &Data<LemmyContext>,
243 ) -> LemmyResult<()> {
244   let context = context.reset_request_count();
245   let fed_task = async {
246     use SendActivityData::*;
247     match data {
248       CreatePost(post) => {
249         let creator_id = post.creator_id;
250         CreateOrUpdatePage::send(post, creator_id, CreateOrUpdateType::Create, context).await
251       }
252       UpdatePost(post) => {
253         let creator_id = post.creator_id;
254         CreateOrUpdatePage::send(post, creator_id, CreateOrUpdateType::Update, context).await
255       }
256       DeletePost(post, person, data) => {
257         send_apub_delete_in_community_new(
258           person,
259           post.community_id,
260           DeletableObjects::Post(post.into()),
261           None,
262           data.deleted,
263           context,
264         )
265         .await
266       }
267       RemovePost(post, person, data) => {
268         send_apub_delete_in_community_new(
269           person,
270           post.community_id,
271           DeletableObjects::Post(post.into()),
272           data.reason.or_else(|| Some(String::new())),
273           data.removed,
274           context,
275         )
276         .await
277       }
278       LockPost(post, actor, locked) => send_lock_post(post, actor, locked, context).await,
279       FeaturePost(post, actor, featured) => send_feature_post(post, actor, featured, context).await,
280       CreateComment(comment) => {
281         let creator_id = comment.creator_id;
282         CreateOrUpdateNote::send(comment, creator_id, CreateOrUpdateType::Create, context).await
283       }
284       UpdateComment(comment) => {
285         let creator_id = comment.creator_id;
286         CreateOrUpdateNote::send(comment, creator_id, CreateOrUpdateType::Update, context).await
287       }
288       DeleteComment(comment, actor, community) => {
289         let is_deleted = comment.deleted;
290         let deletable = DeletableObjects::Comment(comment.into());
291         send_apub_delete_in_community(actor, community, deletable, None, is_deleted, &context).await
292       }
293       RemoveComment(comment, actor, community, reason) => {
294         let is_removed = comment.removed;
295         let deletable = DeletableObjects::Comment(comment.into());
296         send_apub_delete_in_community(actor, community, deletable, reason, is_removed, &context)
297           .await
298       }
299       LikePostOrComment(object_id, person, community, score) => {
300         send_like_activity(object_id, person, community, score, context).await
301       }
302       FollowCommunity(community, person, follow) => {
303         send_follow_community(community, person, follow, &context).await
304       }
305       UpdateCommunity(actor, community) => send_update_community(community, actor, context).await,
306       DeleteCommunity(actor, community, removed) => {
307         let deletable = DeletableObjects::Community(community.clone().into());
308         send_apub_delete_in_community(actor, community, deletable, None, removed, &context).await
309       }
310       RemoveCommunity(actor, community, reason, removed) => {
311         let deletable = DeletableObjects::Community(community.clone().into());
312         send_apub_delete_in_community(
313           actor,
314           community,
315           deletable,
316           reason.clone().or_else(|| Some(String::new())),
317           removed,
318           &context,
319         )
320         .await
321       }
322       AddModToCommunity(actor, community_id, updated_mod_id, added) => {
323         send_add_mod_to_community(actor, community_id, updated_mod_id, added, context).await
324       }
325       BanFromCommunity(mod_, community_id, target, data) => {
326         send_ban_from_community(mod_, community_id, target, data, context).await
327       }
328       BanFromSite(mod_, target, data) => send_ban_from_site(mod_, target, data, context).await,
329       CreatePrivateMessage(pm) => {
330         send_create_or_update_pm(pm, CreateOrUpdateType::Create, context).await
331       }
332       UpdatePrivateMessage(pm) => {
333         send_create_or_update_pm(pm, CreateOrUpdateType::Update, context).await
334       }
335       DeletePrivateMessage(person, pm, deleted) => {
336         send_apub_delete_private_message(&person.into(), pm, deleted, context).await
337       }
338       DeleteUser(person) => delete_user(person, context).await,
339       CreateReport(url, actor, community, reason) => {
340         Report::send(ObjectId::from(url), actor, community, reason, context).await
341       }
342     }
343   };
344   if *SYNCHRONOUS_FEDERATION {
345     fed_task.await?;
346   } else {
347     spawn_try_task(fed_task);
348   }
349   Ok(())
350 }