]> Untitled Git - lemmy.git/blob - crates/apub/src/activities/mod.rs
3a4754996b282990ddd101f82eed6abeb4ab3044
[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::SendActivity, object_id::ObjectId},
11   deser::context::WithContext,
12 };
13 use activitystreams_kinds::public;
14 use anyhow::anyhow;
15 use lemmy_api_common::utils::blocking;
16 use lemmy_db_schema::source::community::Community;
17 use lemmy_db_views_actor::structs::{CommunityPersonBanView, CommunityView};
18 use lemmy_utils::error::LemmyError;
19 use lemmy_websocket::LemmyContext;
20 use serde::Serialize;
21 use std::ops::Deref;
22 use tracing::info;
23 use url::{ParseError, Url};
24 use uuid::Uuid;
25
26 pub mod block;
27 pub mod community;
28 pub mod create_or_update;
29 pub mod deletion;
30 pub mod following;
31 pub mod voting;
32
33 /// Checks that the specified Url actually identifies a Person (by fetching it), and that the person
34 /// doesn't have a site ban.
35 #[tracing::instrument(skip_all)]
36 async fn verify_person(
37   person_id: &ObjectId<ApubPerson>,
38   context: &LemmyContext,
39   request_counter: &mut i32,
40 ) -> Result<(), LemmyError> {
41   let person = person_id
42     .dereference::<LemmyError>(context, local_instance(context), request_counter)
43     .await?;
44   if person.banned {
45     let err = anyhow!("Person {} is banned", person_id);
46     return Err(LemmyError::from_error_message(err, "banned"));
47   }
48   Ok(())
49 }
50
51 /// Fetches the person and community to verify their type, then checks if person is banned from site
52 /// or community.
53 #[tracing::instrument(skip_all)]
54 pub(crate) async fn verify_person_in_community(
55   person_id: &ObjectId<ApubPerson>,
56   community: &ApubCommunity,
57   context: &LemmyContext,
58   request_counter: &mut i32,
59 ) -> Result<(), LemmyError> {
60   let person = person_id
61     .dereference::<LemmyError>(context, local_instance(context), request_counter)
62     .await?;
63   if person.banned {
64     return Err(LemmyError::from_message("Person is banned from site"));
65   }
66   let person_id = person.id;
67   let community_id = community.id;
68   let is_banned =
69     move |conn: &'_ _| CommunityPersonBanView::get(conn, person_id, community_id).is_ok();
70   if blocking(context.pool(), is_banned).await? {
71     return Err(LemmyError::from_message("Person is banned from community"));
72   }
73
74   Ok(())
75 }
76
77 /// Verify that the actor is a community mod. This check is only run if the community is local,
78 /// because in case of remote communities, admins can also perform mod actions. As admin status
79 /// is not federated, we cant verify their actions remotely.
80 ///
81 /// * `mod_id` - Activitypub ID of the mod or admin who performed the action
82 /// * `object_id` - Activitypub ID of the actor or object that is being moderated
83 /// * `community` - The community inside which moderation is happening
84 #[tracing::instrument(skip_all)]
85 pub(crate) async fn verify_mod_action(
86   mod_id: &ObjectId<ApubPerson>,
87   object_id: &Url,
88   community: &ApubCommunity,
89   context: &LemmyContext,
90   request_counter: &mut i32,
91 ) -> Result<(), LemmyError> {
92   if community.local {
93     let actor = mod_id
94       .dereference::<LemmyError>(context, local_instance(context), request_counter)
95       .await?;
96
97     // Note: this will also return true for admins in addition to mods, but as we dont know about
98     //       remote admins, it doesnt make any difference.
99     let community_id = community.id;
100     let actor_id = actor.id;
101
102     let is_mod_or_admin = blocking(context.pool(), move |conn| {
103       CommunityView::is_mod_or_admin(conn, actor_id, community_id)
104     })
105     .await?;
106
107     // mod action was done either by a community mod or a local admin, so its allowed
108     if is_mod_or_admin {
109       return Ok(());
110     }
111
112     // mod action comes from the same instance as the moderated object, so it was presumably done
113     // by an instance admin and is legitimate (admin status is not federated).
114     if mod_id.inner().domain() == object_id.domain() {
115       return Ok(());
116     }
117
118     // the user is not a valid mod
119     return Err(LemmyError::from_message("Not a mod"));
120   }
121   Ok(())
122 }
123
124 /// For Add/Remove community moderator activities, check that the target field actually contains
125 /// /c/community/moderators. Any different values are unsupported.
126 fn verify_add_remove_moderator_target(
127   target: &Url,
128   community: &ApubCommunity,
129 ) -> Result<(), LemmyError> {
130   if target != &generate_moderators_url(&community.actor_id)?.into() {
131     return Err(LemmyError::from_message("Unkown target url"));
132   }
133   Ok(())
134 }
135
136 pub(crate) fn verify_is_public(to: &[Url], cc: &[Url]) -> Result<(), LemmyError> {
137   if ![to, cc].iter().any(|set| set.contains(&public())) {
138     return Err(LemmyError::from_message("Object is not public"));
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<T: Serialize>(
170   context: &LemmyContext,
171   activity: &T,
172   activity_id: &Url,
173   actor: &dyn ActorType,
174   inboxes: Vec<Url>,
175   sensitive: bool,
176 ) -> Result<(), LemmyError> {
177   if !context.settings().federation.enabled || inboxes.is_empty() {
178     return Ok(());
179   }
180   let activity = WithContext::new(activity, CONTEXT.deref().clone());
181
182   info!("Sending activity {}", activity_id.to_string());
183
184   // Don't send anything to ourselves
185   // TODO: this should be a debug assert
186   let hostname = context.settings().get_hostname_without_port()?;
187   let inboxes: Vec<Url> = inboxes
188     .into_iter()
189     .filter(|i| i.domain().expect("valid inbox url") != hostname)
190     .collect();
191
192   let serialised_activity = serde_json::to_string(&activity)?;
193
194   let object_value = serde_json::to_value(&activity)?;
195   insert_activity(activity_id, object_value, true, sensitive, context.pool()).await?;
196
197   SendActivity {
198     activity_id: activity_id.clone(),
199     actor_public_key: actor.get_public_key(),
200     actor_private_key: actor.private_key().expect("actor has private key"),
201     inboxes,
202     activity: serialised_activity,
203   }
204   .send(local_instance(context))
205   .await?;
206
207   Ok(())
208 }