2 extern crate lazy_static;
5 pub mod activity_queue;
12 use crate::extensions::signatures::PublicKey;
13 use activitystreams::base::AnyBase;
14 use anyhow::{anyhow, Context};
16 use lemmy_api_common::blocking;
17 use lemmy_db_queries::{source::activity::Activity_, ApubObject, DbPool};
18 use lemmy_db_schema::{
23 person::{Person as DbPerson, Person},
25 private_message::PrivateMessage,
30 use lemmy_db_views_actor::community_person_ban_view::CommunityPersonBanView;
31 use lemmy_utils::{location_info, settings::structs::Settings, LemmyError};
32 use lemmy_websocket::LemmyContext;
35 use url::{ParseError, Url};
37 pub static APUB_JSON_CONTENT_TYPE: &str = "application/activity+json";
39 /// Checks if the ID is allowed for sending or receiving.
41 /// In particular, it checks for:
42 /// - federation being enabled (if its disabled, only local URLs are allowed)
43 /// - the correct scheme (either http or https)
44 /// - URL being in the allowlist (if it is active)
45 /// - URL not being in the blocklist (if it is active)
47 pub(crate) fn check_is_apub_id_valid(
49 use_strict_allowlist: bool,
50 ) -> Result<(), LemmyError> {
51 let settings = Settings::get();
52 let domain = apub_id.domain().context(location_info!())?.to_string();
53 let local_instance = settings.get_hostname_without_port()?;
55 if !settings.federation.enabled {
56 return if domain == local_instance {
61 "Trying to connect with {}, but federation is disabled",
69 let host = apub_id.host_str().context(location_info!())?;
70 let host_as_ip = host.parse::<IpAddr>();
71 if host == "localhost" || host_as_ip.is_ok() {
72 return Err(anyhow!("invalid hostname {}: {}", host, apub_id).into());
75 if apub_id.scheme() != Settings::get().get_protocol_string() {
76 return Err(anyhow!("invalid apub id scheme {}: {}", apub_id.scheme(), apub_id).into());
79 // TODO: might be good to put the part above in one method, and below in another
80 // (which only gets called in apub::objects)
81 // -> no that doesnt make sense, we still need the code below for blocklist and strict allowlist
82 if let Some(blocked) = Settings::get().federation.blocked_instances {
83 if blocked.contains(&domain) {
84 return Err(anyhow!("{} is in federation blocklist", domain).into());
88 if let Some(mut allowed) = Settings::get().federation.allowed_instances {
89 // Only check allowlist if this is a community, or strict allowlist is enabled.
90 let strict_allowlist = Settings::get().federation.strict_allowlist;
91 if use_strict_allowlist || strict_allowlist {
92 // need to allow this explicitly because apub receive might contain objects from our local
94 allowed.push(local_instance);
96 if !allowed.contains(&domain) {
97 return Err(anyhow!("{} not in federation allowlist", domain).into());
105 /// Common functions for ActivityPub objects, which are implemented by most (but not all) objects
106 /// and actors in Lemmy.
107 #[async_trait::async_trait(?Send)]
108 pub trait ApubObjectType {
109 async fn send_delete(&self, creator: &DbPerson, context: &LemmyContext)
110 -> Result<(), LemmyError>;
111 async fn send_undo_delete(
114 context: &LemmyContext,
115 ) -> Result<(), LemmyError>;
116 async fn send_remove(&self, mod_: &DbPerson, context: &LemmyContext) -> Result<(), LemmyError>;
117 async fn send_undo_remove(
120 context: &LemmyContext,
121 ) -> Result<(), LemmyError>;
124 /// Common methods provided by ActivityPub actors (community and person). Not all methods are
125 /// implemented by all actors.
126 pub trait ActorType {
127 fn is_local(&self) -> bool;
128 fn actor_id(&self) -> Url;
129 fn name(&self) -> String;
131 // TODO: every actor should have a public key, so this shouldnt be an option (needs to be fixed in db)
132 fn public_key(&self) -> Option<String>;
133 fn private_key(&self) -> Option<String>;
135 fn get_shared_inbox_or_inbox_url(&self) -> Url;
137 /// Outbox URL is not generally used by Lemmy, so it can be generated on the fly (but only for
139 fn get_outbox_url(&self) -> Result<Url, LemmyError> {
141 if !self.is_local() {
142 return Err(anyhow!("get_outbox_url() called for remote actor").into());
145 Ok(Url::parse(&format!("{}/outbox", &self.actor_id()))?)
148 fn get_public_key(&self) -> Result<PublicKey, LemmyError> {
150 id: format!("{}#main-key", self.actor_id()),
151 owner: self.actor_id(),
152 public_key_pem: self.public_key().context(location_info!())?,
157 #[async_trait::async_trait(?Send)]
158 pub trait CommunityType {
159 fn followers_url(&self) -> Url;
160 async fn get_follower_inboxes(&self, pool: &DbPool) -> Result<Vec<Url>, LemmyError>;
162 async fn send_update(&self, mod_: Person, context: &LemmyContext) -> Result<(), LemmyError>;
163 async fn send_delete(&self, mod_: Person, context: &LemmyContext) -> Result<(), LemmyError>;
164 async fn send_undo_delete(&self, mod_: Person, context: &LemmyContext) -> Result<(), LemmyError>;
166 async fn send_remove(&self, context: &LemmyContext) -> Result<(), LemmyError>;
167 async fn send_undo_remove(&self, context: &LemmyContext) -> Result<(), LemmyError>;
169 async fn send_announce(
173 context: &LemmyContext,
174 ) -> Result<(), LemmyError>;
176 async fn send_add_mod(
180 context: &LemmyContext,
181 ) -> Result<(), LemmyError>;
182 async fn send_remove_mod(
186 context: &LemmyContext,
187 ) -> Result<(), LemmyError>;
189 async fn send_block_user(
192 blocked_user: Person,
193 context: &LemmyContext,
194 ) -> Result<(), LemmyError>;
195 async fn send_undo_block_user(
198 blocked_user: Person,
199 context: &LemmyContext,
200 ) -> Result<(), LemmyError>;
203 pub enum EndpointType {
211 /// Generates an apub endpoint for a given domain, IE xyz.tld
212 pub(crate) fn generate_apub_endpoint_for_domain(
213 endpoint_type: EndpointType,
216 ) -> Result<DbUrl, ParseError> {
217 let point = match endpoint_type {
218 EndpointType::Community => "c",
219 EndpointType::Person => "u",
220 EndpointType::Post => "post",
221 EndpointType::Comment => "comment",
222 EndpointType::PrivateMessage => "private_message",
225 Ok(Url::parse(&format!("{}/{}/{}", domain, point, name))?.into())
228 /// Generates the ActivityPub ID for a given object type and ID.
229 pub fn generate_apub_endpoint(
230 endpoint_type: EndpointType,
232 ) -> Result<DbUrl, ParseError> {
233 generate_apub_endpoint_for_domain(
236 &Settings::get().get_protocol_and_hostname(),
240 pub fn generate_followers_url(actor_id: &DbUrl) -> Result<DbUrl, ParseError> {
241 Ok(Url::parse(&format!("{}/followers", actor_id))?.into())
244 pub fn generate_inbox_url(actor_id: &DbUrl) -> Result<DbUrl, ParseError> {
245 Ok(Url::parse(&format!("{}/inbox", actor_id))?.into())
248 pub fn generate_shared_inbox_url(actor_id: &DbUrl) -> Result<DbUrl, LemmyError> {
249 let actor_id: Url = actor_id.clone().into();
253 &actor_id.host_str().context(location_info!())?,
254 if let Some(port) = actor_id.port() {
260 Ok(Url::parse(&url)?.into())
263 pub fn generate_moderators_url(community_id: &DbUrl) -> Result<DbUrl, LemmyError> {
264 Ok(Url::parse(&format!("{}/moderators", community_id))?.into())
267 /// Takes in a shortname of the type dessalines@xyz.tld or dessalines (assumed to be local), and outputs the actor id.
268 /// Used in the API for communities and users.
269 pub fn build_actor_id_from_shortname(
270 endpoint_type: EndpointType,
272 ) -> Result<DbUrl, ParseError> {
273 let split = short_name.split('@').collect::<Vec<&str>>();
277 // If there's no @, its local
278 let domain = if split.len() == 1 {
279 Settings::get().get_protocol_and_hostname()
281 format!("{}://{}", Settings::get().get_protocol_string(), split[1])
284 generate_apub_endpoint_for_domain(endpoint_type, name, &domain)
287 /// Store a sent or received activity in the database, for logging purposes. These records are not
289 pub(crate) async fn insert_activity<T>(
295 ) -> Result<(), LemmyError>
297 T: Serialize + std::fmt::Debug + Send + 'static,
299 let ap_id = ap_id.to_owned().into();
300 blocking(pool, move |conn| {
301 Activity::insert(conn, ap_id, &activity, local, sensitive)
307 pub enum PostOrComment {
308 Comment(Box<Comment>),
313 pub(crate) fn ap_id(&self) -> Url {
315 PostOrComment::Post(p) => p.ap_id.clone(),
316 PostOrComment::Comment(c) => c.ap_id.clone(),
322 /// Tries to find a post or comment in the local database, without any network requests.
323 /// This is used to handle deletions and removals, because in case we dont have the object, we can
324 /// simply ignore the activity.
325 pub(crate) async fn find_post_or_comment_by_id(
326 context: &LemmyContext,
328 ) -> Result<PostOrComment, LemmyError> {
329 let ap_id = apub_id.clone();
330 let post = blocking(context.pool(), move |conn| {
331 Post::read_from_apub_id(conn, &ap_id.into())
334 if let Ok(p) = post {
335 return Ok(PostOrComment::Post(Box::new(p)));
338 let ap_id = apub_id.clone();
339 let comment = blocking(context.pool(), move |conn| {
340 Comment::read_from_apub_id(conn, &ap_id.into())
343 if let Ok(c) = comment {
344 return Ok(PostOrComment::Comment(Box::new(c)));
352 Comment(Box<Comment>),
354 Community(Box<Community>),
355 Person(Box<DbPerson>),
356 PrivateMessage(Box<PrivateMessage>),
359 pub(crate) async fn find_object_by_id(
360 context: &LemmyContext,
362 ) -> Result<Object, LemmyError> {
363 let ap_id = apub_id.clone();
364 if let Ok(pc) = find_post_or_comment_by_id(context, ap_id.to_owned()).await {
366 PostOrComment::Post(p) => Object::Post(Box::new(*p)),
367 PostOrComment::Comment(c) => Object::Comment(Box::new(*c)),
371 let ap_id = apub_id.clone();
372 let person = blocking(context.pool(), move |conn| {
373 DbPerson::read_from_apub_id(conn, &ap_id.into())
376 if let Ok(u) = person {
377 return Ok(Object::Person(Box::new(u)));
380 let ap_id = apub_id.clone();
381 let community = blocking(context.pool(), move |conn| {
382 Community::read_from_apub_id(conn, &ap_id.into())
385 if let Ok(c) = community {
386 return Ok(Object::Community(Box::new(c)));
389 let private_message = blocking(context.pool(), move |conn| {
390 PrivateMessage::read_from_apub_id(conn, &apub_id.into())
393 if let Ok(pm) = private_message {
394 return Ok(Object::PrivateMessage(Box::new(pm)));
400 pub(crate) async fn check_community_or_site_ban(
402 community_id: CommunityId,
404 ) -> Result<(), LemmyError> {
406 return Err(anyhow!("Person is banned from site").into());
408 let person_id = person.id;
410 move |conn: &'_ _| CommunityPersonBanView::get(conn, person_id, community_id).is_ok();
411 if blocking(pool, is_banned).await? {
412 return Err(anyhow!("Person is banned from community").into());