]> Untitled Git - lemmy.git/blob - crates/apub/src/activities/mod.rs
Move @context out of object/activity definitions
[lemmy.git] / crates / apub / src / activities / mod.rs
1 use crate::{
2   check_is_apub_id_valid,
3   context::WithContext,
4   fetcher::object_id::ObjectId,
5   generate_moderators_url,
6   insert_activity,
7   objects::{community::ApubCommunity, person::ApubPerson},
8 };
9 use activitystreams::public;
10 use anyhow::anyhow;
11 use lemmy_api_common::blocking;
12 use lemmy_apub_lib::{
13   activity_queue::send_activity,
14   traits::{ActivityFields, 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 log::info;
25 use serde::{Deserialize, Serialize};
26 use strum_macros::ToString;
27 use url::{ParseError, Url};
28 use uuid::Uuid;
29
30 pub mod comment;
31 pub mod community;
32 pub mod deletion;
33 pub mod following;
34 pub mod post;
35 pub mod private_message;
36 pub mod report;
37 pub mod voting;
38
39 #[derive(Clone, Debug, ToString, Deserialize, Serialize)]
40 pub enum CreateOrUpdateType {
41   Create,
42   Update,
43 }
44
45 /// Checks that the specified Url actually identifies a Person (by fetching it), and that the person
46 /// doesn't have a site ban.
47 async fn verify_person(
48   person_id: &ObjectId<ApubPerson>,
49   context: &LemmyContext,
50   request_counter: &mut i32,
51 ) -> Result<(), LemmyError> {
52   let person = person_id.dereference(context, request_counter).await?;
53   if person.banned {
54     return Err(anyhow!("Person {} is banned", person_id).into());
55   }
56   Ok(())
57 }
58
59 /// Fetches the person and community to verify their type, then checks if person is banned from site
60 /// or community.
61 pub(crate) async fn verify_person_in_community(
62   person_id: &ObjectId<ApubPerson>,
63   community: &ApubCommunity,
64   context: &LemmyContext,
65   request_counter: &mut i32,
66 ) -> Result<(), LemmyError> {
67   let person = person_id.dereference(context, request_counter).await?;
68   if person.banned {
69     return Err(anyhow!("Person is banned from site").into());
70   }
71   let person_id = person.id;
72   let community_id = community.id;
73   let is_banned =
74     move |conn: &'_ _| CommunityPersonBanView::get(conn, person_id, community_id).is_ok();
75   if blocking(context.pool(), is_banned).await? {
76     return Err(anyhow!("Person is banned from community").into());
77   }
78
79   Ok(())
80 }
81
82 fn verify_activity(activity: &dyn ActivityFields, settings: &Settings) -> Result<(), LemmyError> {
83   check_is_apub_id_valid(activity.actor(), false, settings)?;
84   verify_domains_match(activity.id_unchecked(), activity.actor())?;
85   Ok(())
86 }
87
88 /// Verify that the actor is a community mod. This check is only run if the community is local,
89 /// because in case of remote communities, admins can also perform mod actions. As admin status
90 /// is not federated, we cant verify their actions remotely.
91 pub(crate) async fn verify_mod_action(
92   actor_id: &ObjectId<ApubPerson>,
93   community: &ApubCommunity,
94   context: &LemmyContext,
95   request_counter: &mut i32,
96 ) -> Result<(), LemmyError> {
97   if community.local {
98     let actor = actor_id.dereference(context, request_counter).await?;
99
100     // Note: this will also return true for admins in addition to mods, but as we dont know about
101     //       remote admins, it doesnt make any difference.
102     let community_id = community.id;
103     let actor_id = actor.id;
104     let is_mod_or_admin = blocking(context.pool(), move |conn| {
105       CommunityView::is_mod_or_admin(conn, actor_id, community_id)
106     })
107     .await?;
108     if !is_mod_or_admin {
109       return Err(anyhow!("Not a mod").into());
110     }
111   }
112   Ok(())
113 }
114
115 /// For Add/Remove community moderator activities, check that the target field actually contains
116 /// /c/community/moderators. Any different values are unsupported.
117 fn verify_add_remove_moderator_target(
118   target: &Url,
119   community: &ApubCommunity,
120 ) -> Result<(), LemmyError> {
121   if target != &generate_moderators_url(&community.actor_id)?.into_inner() {
122     return Err(anyhow!("Unkown target url").into());
123   }
124   Ok(())
125 }
126
127 pub(crate) fn verify_is_public(to: &[Url]) -> Result<(), LemmyError> {
128   if !to.contains(&public()) {
129     return Err(anyhow!("Object is not public").into());
130   }
131   Ok(())
132 }
133
134 pub(crate) fn check_community_deleted_or_removed(community: &Community) -> Result<(), LemmyError> {
135   if community.deleted || community.removed {
136     Err(anyhow!("New post or comment cannot be created in deleted or removed community").into())
137   } else {
138     Ok(())
139   }
140 }
141
142 /// Generate a unique ID for an activity, in the format:
143 /// `http(s)://example.com/receive/create/202daf0a-1489-45df-8d2e-c8a3173fed36`
144 fn generate_activity_id<T>(kind: T, protocol_and_hostname: &str) -> Result<Url, ParseError>
145 where
146   T: ToString,
147 {
148   let id = format!(
149     "{}/activities/{}/{}",
150     protocol_and_hostname,
151     kind.to_string().to_lowercase(),
152     Uuid::new_v4()
153   );
154   Url::parse(&id)
155 }
156
157 async fn send_lemmy_activity<T: Serialize>(
158   context: &LemmyContext,
159   activity: &T,
160   activity_id: &Url,
161   actor: &dyn ActorType,
162   inboxes: Vec<Url>,
163   sensitive: bool,
164 ) -> Result<(), LemmyError> {
165   if !context.settings().federation.enabled || inboxes.is_empty() {
166     return Ok(());
167   }
168   let activity = WithContext::new(activity);
169
170   info!("Sending activity {}", activity_id.to_string());
171
172   // Don't send anything to ourselves
173   // TODO: this should be a debug assert
174   let hostname = context.settings().get_hostname_without_port()?;
175   let inboxes: Vec<&Url> = inboxes
176     .iter()
177     .filter(|i| i.domain().expect("valid inbox url") != hostname)
178     .collect();
179
180   let serialised_activity = serde_json::to_string(&activity)?;
181
182   insert_activity(
183     activity_id,
184     serialised_activity.clone(),
185     true,
186     sensitive,
187     context.pool(),
188   )
189   .await?;
190
191   send_activity(
192     serialised_activity,
193     actor,
194     inboxes,
195     context.client(),
196     context.activity_queue(),
197   )
198   .await
199 }