]> Untitled Git - lemmy.git/blob - crates/apub/src/activities/mod.rs
77d4883f00a764dc5e8aab9697da45ad1a5f9038
[lemmy.git] / crates / apub / src / activities / mod.rs
1 use crate::{
2   check_is_apub_id_valid,
3   context::WithContext,
4   generate_moderators_url,
5   insert_activity,
6   objects::{community::ApubCommunity, person::ApubPerson},
7 };
8 use activitystreams_kinds::public;
9 use anyhow::anyhow;
10 use lemmy_api_common::blocking;
11 use lemmy_apub_lib::{
12   activity_queue::send_activity,
13   object_id::ObjectId,
14   traits::ActorType,
15   verify::verify_domains_match,
16 };
17 use lemmy_db_schema::source::community::Community;
18 use lemmy_db_views_actor::{
19   community_person_ban_view::CommunityPersonBanView,
20   community_view::CommunityView,
21 };
22 use lemmy_utils::{settings::structs::Settings, LemmyError};
23 use lemmy_websocket::LemmyContext;
24 use serde::Serialize;
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, context.client(), 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, context.client(), 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 =
72     move |conn: &'_ _| CommunityPersonBanView::get(conn, person_id, community_id).is_ok();
73   if blocking(context.pool(), is_banned).await? {
74     return Err(LemmyError::from_message("Person is banned from community"));
75   }
76
77   Ok(())
78 }
79
80 fn verify_activity(id: &Url, actor: &Url, settings: &Settings) -> Result<(), LemmyError> {
81   check_is_apub_id_valid(actor, false, settings)?;
82   verify_domains_match(id, actor)?;
83   Ok(())
84 }
85
86 /// Verify that the actor is a community mod. This check is only run if the community is local,
87 /// because in case of remote communities, admins can also perform mod actions. As admin status
88 /// is not federated, we cant verify their actions remotely.
89 ///
90 /// * `mod_id` - Activitypub ID of the mod or admin who performed the action
91 /// * `object_id` - Activitypub ID of the actor or object that is being moderated
92 /// * `community` - The community inside which moderation is happening
93 #[tracing::instrument(skip_all)]
94 pub(crate) async fn verify_mod_action(
95   mod_id: &ObjectId<ApubPerson>,
96   object_id: &Url,
97   community: &ApubCommunity,
98   context: &LemmyContext,
99   request_counter: &mut i32,
100 ) -> Result<(), LemmyError> {
101   if community.local {
102     let actor = mod_id
103       .dereference(context, context.client(), request_counter)
104       .await?;
105
106     // Note: this will also return true for admins in addition to mods, but as we dont know about
107     //       remote admins, it doesnt make any difference.
108     let community_id = community.id;
109     let actor_id = actor.id;
110
111     let is_mod_or_admin = blocking(context.pool(), move |conn| {
112       CommunityView::is_mod_or_admin(conn, actor_id, community_id)
113     })
114     .await?;
115
116     // mod action was done either by a community mod or a local admin, so its allowed
117     if is_mod_or_admin {
118       return Ok(());
119     }
120
121     // mod action comes from the same instance as the moderated object, so it was presumably done
122     // by an instance admin and is legitimate (admin status is not federated).
123     if mod_id.inner().domain() == object_id.domain() {
124       return Ok(());
125     }
126
127     // the user is not a valid mod
128     return Err(LemmyError::from_message("Not a mod"));
129   }
130   Ok(())
131 }
132
133 /// For Add/Remove community moderator activities, check that the target field actually contains
134 /// /c/community/moderators. Any different values are unsupported.
135 fn verify_add_remove_moderator_target(
136   target: &Url,
137   community: &ApubCommunity,
138 ) -> Result<(), LemmyError> {
139   if target != &generate_moderators_url(&community.actor_id)?.into() {
140     return Err(LemmyError::from_message("Unkown target url"));
141   }
142   Ok(())
143 }
144
145 pub(crate) fn verify_is_public(to: &[Url], cc: &[Url]) -> Result<(), LemmyError> {
146   if ![to, cc].iter().any(|set| set.contains(&public())) {
147     return Err(LemmyError::from_message("Object is not public"));
148   }
149   Ok(())
150 }
151
152 pub(crate) fn check_community_deleted_or_removed(community: &Community) -> Result<(), LemmyError> {
153   if community.deleted || community.removed {
154     Err(LemmyError::from_message(
155       "New post or comment cannot be created in deleted or removed community",
156     ))
157   } else {
158     Ok(())
159   }
160 }
161
162 /// Generate a unique ID for an activity, in the format:
163 /// `http(s)://example.com/receive/create/202daf0a-1489-45df-8d2e-c8a3173fed36`
164 fn generate_activity_id<T>(kind: T, protocol_and_hostname: &str) -> Result<Url, ParseError>
165 where
166   T: ToString,
167 {
168   let id = format!(
169     "{}/activities/{}/{}",
170     protocol_and_hostname,
171     kind.to_string().to_lowercase(),
172     Uuid::new_v4()
173   );
174   Url::parse(&id)
175 }
176
177 #[tracing::instrument(skip_all)]
178 async fn send_lemmy_activity<T: Serialize>(
179   context: &LemmyContext,
180   activity: &T,
181   activity_id: &Url,
182   actor: &dyn ActorType,
183   inboxes: Vec<Url>,
184   sensitive: bool,
185 ) -> Result<(), LemmyError> {
186   if !context.settings().federation.enabled || inboxes.is_empty() {
187     return Ok(());
188   }
189   let activity = WithContext::new(activity);
190
191   info!("Sending activity {}", activity_id.to_string());
192
193   // Don't send anything to ourselves
194   // TODO: this should be a debug assert
195   let hostname = context.settings().get_hostname_without_port()?;
196   let inboxes: Vec<&Url> = inboxes
197     .iter()
198     .filter(|i| i.domain().expect("valid inbox url") != hostname)
199     .collect();
200
201   let serialised_activity = serde_json::to_string(&activity)?;
202
203   let object_value = serde_json::to_value(&activity)?;
204   insert_activity(activity_id, object_value, true, sensitive, context.pool()).await?;
205
206   send_activity(
207     activity_id,
208     actor,
209     inboxes,
210     serialised_activity,
211     context.client(),
212     context.activity_queue(),
213   )
214   .await
215 }