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