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