]> Untitled Git - lemmy.git/blob - crates/apub/src/activities/mod.rs
68a3b535c10bd16ddb5c9b6c7e1d5a2e4c4fcab2
[lemmy.git] / crates / apub / src / activities / mod.rs
1 use crate::{
2   insert_activity,
3   local_instance,
4   objects::{community::ApubCommunity, person::ApubPerson},
5   ActorType,
6   CONTEXT,
7 };
8 use activitypub_federation::{
9   core::{activity_queue::send_activity, object_id::ObjectId},
10   deser::context::WithContext,
11   traits::{ActivityHandler, Actor},
12 };
13 use activitystreams_kinds::public;
14 use anyhow::anyhow;
15 use lemmy_api_common::{generate_moderators_url, LemmyContext};
16 use lemmy_db_schema::{
17   newtypes::CommunityId,
18   source::{community::Community, local_site::LocalSite},
19 };
20 use lemmy_db_views_actor::structs::{CommunityPersonBanView, CommunityView};
21 use lemmy_utils::error::LemmyError;
22 use serde::Serialize;
23 use std::ops::Deref;
24 use tracing::info;
25 use url::{ParseError, Url};
26 use uuid::Uuid;
27
28 pub mod block;
29 pub mod community;
30 pub mod create_or_update;
31 pub mod deletion;
32 pub mod following;
33 pub mod voting;
34
35 /// Checks that the specified Url actually identifies a Person (by fetching it), and that the person
36 /// doesn't have a site ban.
37 #[tracing::instrument(skip_all)]
38 async fn verify_person(
39   person_id: &ObjectId<ApubPerson>,
40   context: &LemmyContext,
41   request_counter: &mut i32,
42 ) -> Result<(), LemmyError> {
43   let person = person_id
44     .dereference(context, local_instance(context).await, request_counter)
45     .await?;
46   if person.banned {
47     let err = anyhow!("Person {} is banned", person_id);
48     return Err(LemmyError::from_error_message(err, "banned"));
49   }
50   Ok(())
51 }
52
53 /// Fetches the person and community to verify their type, then checks if person is banned from site
54 /// or community.
55 #[tracing::instrument(skip_all)]
56 pub(crate) async fn verify_person_in_community(
57   person_id: &ObjectId<ApubPerson>,
58   community: &ApubCommunity,
59   context: &LemmyContext,
60   request_counter: &mut i32,
61 ) -> Result<(), LemmyError> {
62   let person = person_id
63     .dereference(context, local_instance(context).await, request_counter)
64     .await?;
65   if person.banned {
66     return Err(LemmyError::from_message("Person is banned from site"));
67   }
68   let person_id = person.id;
69   let community_id = community.id;
70   let is_banned = CommunityPersonBanView::get(context.pool(), person_id, community_id)
71     .await
72     .is_ok();
73   if is_banned {
74     return Err(LemmyError::from_message("Person is banned from community"));
75   }
76
77   Ok(())
78 }
79
80 /// Verify that mod action in community was performed by a moderator.
81 ///
82 /// * `mod_id` - Activitypub ID of the mod or admin who performed the action
83 /// * `object_id` - Activitypub ID of the actor or object that is being moderated
84 /// * `community` - The community inside which moderation is happening
85 #[tracing::instrument(skip_all)]
86 pub(crate) async fn verify_mod_action(
87   mod_id: &ObjectId<ApubPerson>,
88   object_id: &Url,
89   community_id: CommunityId,
90   context: &LemmyContext,
91   request_counter: &mut i32,
92 ) -> Result<(), LemmyError> {
93   let mod_ = mod_id
94     .dereference(context, local_instance(context).await, request_counter)
95     .await?;
96
97   let is_mod_or_admin =
98     CommunityView::is_mod_or_admin(context.pool(), mod_.id, community_id).await?;
99   if is_mod_or_admin {
100     return Ok(());
101   }
102
103   // mod action comes from the same instance as the moderated object, so it was presumably done
104   // by an instance admin.
105   // TODO: federate instance admin status and check it here
106   if mod_id.inner().domain() == object_id.domain() {
107     return Ok(());
108   }
109
110   Err(LemmyError::from_message("Not a mod"))
111 }
112
113 /// For Add/Remove community moderator activities, check that the target field actually contains
114 /// /c/community/moderators. Any different values are unsupported.
115 fn verify_add_remove_moderator_target(
116   target: &Url,
117   community: &ApubCommunity,
118 ) -> Result<(), LemmyError> {
119   if target != &generate_moderators_url(&community.actor_id)?.into() {
120     return Err(LemmyError::from_message("Unkown target url"));
121   }
122   Ok(())
123 }
124
125 pub(crate) fn verify_is_public(to: &[Url], cc: &[Url]) -> Result<(), LemmyError> {
126   if ![to, cc].iter().any(|set| set.contains(&public())) {
127     return Err(LemmyError::from_message("Object is not public"));
128   }
129   Ok(())
130 }
131
132 pub(crate) fn verify_community_matches(
133   a: &ApubCommunity,
134   b: CommunityId,
135 ) -> Result<(), LemmyError> {
136   if a.id != b {
137     return Err(LemmyError::from_message("Invalid community"));
138   }
139   Ok(())
140 }
141
142 pub(crate) fn check_community_deleted_or_removed(community: &Community) -> Result<(), LemmyError> {
143   if community.deleted || community.removed {
144     Err(LemmyError::from_message(
145       "New post or comment cannot be created in deleted or removed community",
146     ))
147   } else {
148     Ok(())
149   }
150 }
151
152 /// Generate a unique ID for an activity, in the format:
153 /// `http(s)://example.com/receive/create/202daf0a-1489-45df-8d2e-c8a3173fed36`
154 fn generate_activity_id<T>(kind: T, protocol_and_hostname: &str) -> Result<Url, ParseError>
155 where
156   T: ToString,
157 {
158   let id = format!(
159     "{}/activities/{}/{}",
160     protocol_and_hostname,
161     kind.to_string().to_lowercase(),
162     Uuid::new_v4()
163   );
164   Url::parse(&id)
165 }
166
167 #[tracing::instrument(skip_all)]
168 async fn send_lemmy_activity<Activity, ActorT>(
169   context: &LemmyContext,
170   activity: Activity,
171   actor: &ActorT,
172   inbox: Vec<Url>,
173   sensitive: bool,
174 ) -> Result<(), LemmyError>
175 where
176   Activity: ActivityHandler + Serialize,
177   ActorT: Actor + ActorType,
178   Activity: ActivityHandler<Error = LemmyError>,
179 {
180   let federation_enabled = LocalSite::read(context.pool())
181     .await
182     .map(|l| l.federation_enabled)
183     .unwrap_or(false);
184   if !federation_enabled {
185     return Ok(());
186   }
187
188   info!("Sending activity {}", activity.id().to_string());
189   let activity = WithContext::new(activity, CONTEXT.deref().clone());
190
191   let object_value = serde_json::to_value(&activity)?;
192   insert_activity(activity.id(), object_value, true, sensitive, context.pool()).await?;
193
194   send_activity(
195     activity,
196     actor.get_public_key(),
197     actor.private_key().expect("actor has private key"),
198     inbox,
199     local_instance(context).await,
200   )
201   .await?;
202
203   Ok(())
204 }