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