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