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