]> Untitled Git - lemmy.git/blob - crates/apub/src/activities/mod.rs
Merge websocket crate into api_common
[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::LemmyContext;
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 serde::Serialize;
24 use std::ops::Deref;
25 use tracing::info;
26 use url::{ParseError, Url};
27 use uuid::Uuid;
28
29 pub mod block;
30 pub mod community;
31 pub mod create_or_update;
32 pub mod deletion;
33 pub mod following;
34 pub mod voting;
35
36 /// Checks that the specified Url actually identifies a Person (by fetching it), and that the person
37 /// doesn't have a site ban.
38 #[tracing::instrument(skip_all)]
39 async fn verify_person(
40   person_id: &ObjectId<ApubPerson>,
41   context: &LemmyContext,
42   request_counter: &mut i32,
43 ) -> Result<(), LemmyError> {
44   let person = person_id
45     .dereference(context, local_instance(context).await, request_counter)
46     .await?;
47   if person.banned {
48     let err = anyhow!("Person {} is banned", person_id);
49     return Err(LemmyError::from_error_message(err, "banned"));
50   }
51   Ok(())
52 }
53
54 /// Fetches the person and community to verify their type, then checks if person is banned from site
55 /// or community.
56 #[tracing::instrument(skip_all)]
57 pub(crate) async fn verify_person_in_community(
58   person_id: &ObjectId<ApubPerson>,
59   community: &ApubCommunity,
60   context: &LemmyContext,
61   request_counter: &mut i32,
62 ) -> Result<(), LemmyError> {
63   let person = person_id
64     .dereference(context, local_instance(context).await, request_counter)
65     .await?;
66   if person.banned {
67     return Err(LemmyError::from_message("Person is banned from site"));
68   }
69   let person_id = person.id;
70   let community_id = community.id;
71   let is_banned = CommunityPersonBanView::get(context.pool(), person_id, community_id)
72     .await
73     .is_ok();
74   if is_banned {
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).await, request_counter)
96     .await?;
97
98   let is_mod_or_admin =
99     CommunityView::is_mod_or_admin(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(LemmyError::from_message("Not a mod"))
112 }
113
114 /// For Add/Remove community moderator activities, check that the target field actually contains
115 /// /c/community/moderators. Any different values are unsupported.
116 fn verify_add_remove_moderator_target(
117   target: &Url,
118   community: &ApubCommunity,
119 ) -> Result<(), LemmyError> {
120   if target != &generate_moderators_url(&community.actor_id)?.into() {
121     return Err(LemmyError::from_message("Unkown target url"));
122   }
123   Ok(())
124 }
125
126 pub(crate) fn verify_is_public(to: &[Url], cc: &[Url]) -> Result<(), LemmyError> {
127   if ![to, cc].iter().any(|set| set.contains(&public())) {
128     return Err(LemmyError::from_message("Object is not public"));
129   }
130   Ok(())
131 }
132
133 pub(crate) fn verify_community_matches(
134   a: &ApubCommunity,
135   b: CommunityId,
136 ) -> Result<(), LemmyError> {
137   if a.id != b {
138     return Err(LemmyError::from_message("Invalid community"));
139   }
140   Ok(())
141 }
142
143 pub(crate) fn check_community_deleted_or_removed(community: &Community) -> Result<(), LemmyError> {
144   if community.deleted || community.removed {
145     Err(LemmyError::from_message(
146       "New post or comment cannot be created in deleted or removed community",
147     ))
148   } else {
149     Ok(())
150   }
151 }
152
153 /// Generate a unique ID for an activity, in the format:
154 /// `http(s)://example.com/receive/create/202daf0a-1489-45df-8d2e-c8a3173fed36`
155 fn generate_activity_id<T>(kind: T, protocol_and_hostname: &str) -> Result<Url, ParseError>
156 where
157   T: ToString,
158 {
159   let id = format!(
160     "{}/activities/{}/{}",
161     protocol_and_hostname,
162     kind.to_string().to_lowercase(),
163     Uuid::new_v4()
164   );
165   Url::parse(&id)
166 }
167
168 #[tracing::instrument(skip_all)]
169 async fn send_lemmy_activity<Activity, ActorT>(
170   context: &LemmyContext,
171   activity: Activity,
172   actor: &ActorT,
173   inbox: Vec<Url>,
174   sensitive: bool,
175 ) -> Result<(), LemmyError>
176 where
177   Activity: ActivityHandler + Serialize,
178   ActorT: Actor + ActorType,
179   Activity: ActivityHandler<Error = LemmyError>,
180 {
181   let federation_enabled = LocalSite::read(context.pool())
182     .await
183     .map(|l| l.federation_enabled)
184     .unwrap_or(false);
185   if !federation_enabled {
186     return Ok(());
187   }
188
189   info!("Sending activity {}", activity.id().to_string());
190   let activity = WithContext::new(activity, CONTEXT.deref().clone());
191
192   let object_value = serde_json::to_value(&activity)?;
193   insert_activity(activity.id(), object_value, true, sensitive, context.pool()).await?;
194
195   send_activity(
196     activity,
197     actor.get_public_key(),
198     actor.private_key().expect("actor has private key"),
199     inbox,
200     local_instance(context).await,
201   )
202   .await?;
203
204   Ok(())
205 }