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