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