2 extern crate lazy_static;
5 pub mod activity_queue;
13 group_extension::GroupExtension,
14 page_extension::PageExtension,
15 person_extension::PersonExtension,
16 signatures::{PublicKey, PublicKeyExtension},
18 fetcher::community::get_or_fetch_and_upsert_community,
20 use activitystreams::{
24 object::{ApObject, AsObject, Note, ObjectExt, Page},
26 use activitystreams_ext::{Ext1, Ext2};
27 use anyhow::{anyhow, Context};
29 use lemmy_api_common::blocking;
30 use lemmy_db_queries::{source::activity::Activity_, ApubObject, DbPool};
31 use lemmy_db_schema::{
36 person::{Person as DbPerson, Person},
38 private_message::PrivateMessage,
43 use lemmy_db_views_actor::community_person_ban_view::CommunityPersonBanView;
44 use lemmy_utils::{location_info, settings::structs::Settings, LemmyError};
45 use lemmy_websocket::LemmyContext;
48 use url::{ParseError, Url};
50 /// Activitystreams type for community
52 Ext2<actor::ApActor<ApObject<actor::Group>>, GroupExtension, PublicKeyExtension>;
53 /// Activitystreams type for person
55 Ext2<actor::ApActor<ApObject<actor::Actor<UserTypes>>>, PersonExtension, PublicKeyExtension>;
56 pub type SiteExt = actor::ApActor<ApObject<actor::Service>>;
57 /// Activitystreams type for post
58 pub type PageExt = Ext1<ApObject<Page>, PageExtension>;
59 pub type NoteExt = ApObject<Note>;
61 #[derive(Clone, Copy, Debug, serde::Deserialize, serde::Serialize, PartialEq)]
67 pub static APUB_JSON_CONTENT_TYPE: &str = "application/activity+json";
69 /// Checks if the ID is allowed for sending or receiving.
71 /// In particular, it checks for:
72 /// - federation being enabled (if its disabled, only local URLs are allowed)
73 /// - the correct scheme (either http or https)
74 /// - URL being in the allowlist (if it is active)
75 /// - URL not being in the blocklist (if it is active)
77 pub fn check_is_apub_id_valid(apub_id: &Url, use_strict_allowlist: bool) -> Result<(), LemmyError> {
78 let settings = Settings::get();
79 let domain = apub_id.domain().context(location_info!())?.to_string();
80 let local_instance = settings.get_hostname_without_port()?;
82 if !settings.federation().enabled {
83 return if domain == local_instance {
88 "Trying to connect with {}, but federation is disabled",
96 let host = apub_id.host_str().context(location_info!())?;
97 let host_as_ip = host.parse::<IpAddr>();
98 if host == "localhost" || host_as_ip.is_ok() {
99 return Err(anyhow!("invalid hostname {}: {}", host, apub_id).into());
102 if apub_id.scheme() != Settings::get().get_protocol_string() {
103 return Err(anyhow!("invalid apub id scheme {}: {}", apub_id.scheme(), apub_id).into());
106 // TODO: might be good to put the part above in one method, and below in another
107 // (which only gets called in apub::objects)
108 // -> no that doesnt make sense, we still need the code below for blocklist and strict allowlist
109 if let Some(blocked) = Settings::get().get_blocked_instances() {
110 if blocked.contains(&domain) {
111 return Err(anyhow!("{} is in federation blocklist", domain).into());
115 if let Some(mut allowed) = Settings::get().get_allowed_instances() {
116 // Only check allowlist if this is a community, or strict allowlist is enabled.
117 let strict_allowlist = Settings::get()
121 if use_strict_allowlist || strict_allowlist {
122 // need to allow this explicitly because apub receive might contain objects from our local
124 allowed.push(local_instance);
126 if !allowed.contains(&domain) {
127 return Err(anyhow!("{} not in federation allowlist", domain).into());
135 /// Common functions for ActivityPub objects, which are implemented by most (but not all) objects
136 /// and actors in Lemmy.
137 #[async_trait::async_trait(?Send)]
138 pub trait ApubObjectType {
139 async fn send_create(&self, creator: &DbPerson, context: &LemmyContext)
140 -> Result<(), LemmyError>;
141 async fn send_update(&self, creator: &DbPerson, context: &LemmyContext)
142 -> Result<(), LemmyError>;
143 async fn send_delete(&self, creator: &DbPerson, context: &LemmyContext)
144 -> Result<(), LemmyError>;
145 async fn send_undo_delete(
148 context: &LemmyContext,
149 ) -> Result<(), LemmyError>;
150 async fn send_remove(&self, mod_: &DbPerson, context: &LemmyContext) -> Result<(), LemmyError>;
151 async fn send_undo_remove(
154 context: &LemmyContext,
155 ) -> Result<(), LemmyError>;
158 #[async_trait::async_trait(?Send)]
159 pub trait ApubLikeableType {
160 async fn send_like(&self, creator: &DbPerson, context: &LemmyContext) -> Result<(), LemmyError>;
161 async fn send_dislike(
164 context: &LemmyContext,
165 ) -> Result<(), LemmyError>;
166 async fn send_undo_like(
169 context: &LemmyContext,
170 ) -> Result<(), LemmyError>;
173 /// Common methods provided by ActivityPub actors (community and person). Not all methods are
174 /// implemented by all actors.
175 pub trait ActorType {
176 fn is_local(&self) -> bool;
177 fn actor_id(&self) -> Url;
178 fn name(&self) -> String;
180 // TODO: every actor should have a public key, so this shouldnt be an option (needs to be fixed in db)
181 fn public_key(&self) -> Option<String>;
182 fn private_key(&self) -> Option<String>;
184 fn get_shared_inbox_or_inbox_url(&self) -> Url;
186 /// Outbox URL is not generally used by Lemmy, so it can be generated on the fly (but only for
188 fn get_outbox_url(&self) -> Result<Url, LemmyError> {
190 if !self.is_local() {
191 return Err(anyhow!("get_outbox_url() called for remote actor").into());
194 Ok(Url::parse(&format!("{}/outbox", &self.actor_id()))?)
197 fn get_public_key_ext(&self) -> Result<PublicKeyExtension, LemmyError> {
200 id: format!("{}#main-key", self.actor_id()),
201 owner: self.actor_id(),
202 public_key_pem: self.public_key().context(location_info!())?,
209 #[async_trait::async_trait(?Send)]
210 pub trait CommunityType {
211 fn followers_url(&self) -> Url;
212 async fn get_follower_inboxes(&self, pool: &DbPool) -> Result<Vec<Url>, LemmyError>;
213 async fn send_accept_follow(
216 context: &LemmyContext,
217 ) -> Result<(), LemmyError>;
219 async fn send_update(&self, mod_: Person, context: &LemmyContext) -> Result<(), LemmyError>;
220 async fn send_delete(&self, mod_: Person, context: &LemmyContext) -> Result<(), LemmyError>;
221 async fn send_undo_delete(&self, mod_: Person, context: &LemmyContext) -> Result<(), LemmyError>;
223 async fn send_remove(&self, context: &LemmyContext) -> Result<(), LemmyError>;
224 async fn send_undo_remove(&self, context: &LemmyContext) -> Result<(), LemmyError>;
226 async fn send_announce(
230 context: &LemmyContext,
231 ) -> Result<(), LemmyError>;
233 async fn send_add_mod(
237 context: &LemmyContext,
238 ) -> Result<(), LemmyError>;
239 async fn send_remove_mod(
243 context: &LemmyContext,
244 ) -> Result<(), LemmyError>;
246 async fn send_block_user(
249 blocked_user: Person,
250 context: &LemmyContext,
251 ) -> Result<(), LemmyError>;
252 async fn send_undo_block_user(
255 blocked_user: Person,
256 context: &LemmyContext,
257 ) -> Result<(), LemmyError>;
260 #[async_trait::async_trait(?Send)]
262 async fn send_follow(
264 follow_actor_id: &Url,
265 context: &LemmyContext,
266 ) -> Result<(), LemmyError>;
267 async fn send_unfollow(
269 follow_actor_id: &Url,
270 context: &LemmyContext,
271 ) -> Result<(), LemmyError>;
274 pub enum EndpointType {
282 /// Generates an apub endpoint for a given domain, IE xyz.tld
283 pub fn generate_apub_endpoint_for_domain(
284 endpoint_type: EndpointType,
287 ) -> Result<DbUrl, ParseError> {
288 let point = match endpoint_type {
289 EndpointType::Community => "c",
290 EndpointType::Person => "u",
291 EndpointType::Post => "post",
292 EndpointType::Comment => "comment",
293 EndpointType::PrivateMessage => "private_message",
296 Ok(Url::parse(&format!("{}/{}/{}", domain, point, name))?.into())
299 /// Generates the ActivityPub ID for a given object type and ID.
300 pub fn generate_apub_endpoint(
301 endpoint_type: EndpointType,
303 ) -> Result<DbUrl, ParseError> {
304 generate_apub_endpoint_for_domain(
307 &Settings::get().get_protocol_and_hostname(),
311 pub fn generate_followers_url(actor_id: &DbUrl) -> Result<DbUrl, ParseError> {
312 Ok(Url::parse(&format!("{}/followers", actor_id))?.into())
315 pub fn generate_inbox_url(actor_id: &DbUrl) -> Result<DbUrl, ParseError> {
316 Ok(Url::parse(&format!("{}/inbox", actor_id))?.into())
319 pub fn generate_shared_inbox_url(actor_id: &DbUrl) -> Result<DbUrl, LemmyError> {
320 let actor_id = actor_id.clone().into_inner();
324 &actor_id.host_str().context(location_info!())?,
325 if let Some(port) = actor_id.port() {
331 Ok(Url::parse(&url)?.into())
334 pub fn generate_moderators_url(community_id: &DbUrl) -> Result<DbUrl, LemmyError> {
335 Ok(Url::parse(&format!("{}/moderators", community_id))?.into())
338 /// Takes in a shortname of the type dessalines@xyz.tld or dessalines (assumed to be local), and outputs the actor id.
339 /// Used in the API for communities and users.
340 pub fn build_actor_id_from_shortname(
341 endpoint_type: EndpointType,
343 ) -> Result<DbUrl, ParseError> {
344 let split = short_name.split('@').collect::<Vec<&str>>();
348 // If there's no @, its local
349 let domain = if split.len() == 1 {
350 Settings::get().get_protocol_and_hostname()
352 format!("{}://{}", Settings::get().get_protocol_string(), split[1])
355 generate_apub_endpoint_for_domain(endpoint_type, name, &domain)
358 /// Store a sent or received activity in the database, for logging purposes. These records are not
360 pub async fn insert_activity<T>(
366 ) -> Result<(), LemmyError>
368 T: Serialize + std::fmt::Debug + Send + 'static,
370 let ap_id = ap_id.to_owned().into();
371 blocking(pool, move |conn| {
372 Activity::insert(conn, ap_id, &activity, local, sensitive)
378 pub enum PostOrComment {
379 Comment(Box<Comment>),
383 /// Tries to find a post or comment in the local database, without any network requests.
384 /// This is used to handle deletions and removals, because in case we dont have the object, we can
385 /// simply ignore the activity.
386 pub async fn find_post_or_comment_by_id(
387 context: &LemmyContext,
389 ) -> Result<PostOrComment, LemmyError> {
390 let ap_id = apub_id.clone();
391 let post = blocking(context.pool(), move |conn| {
392 Post::read_from_apub_id(conn, &ap_id.into())
395 if let Ok(p) = post {
396 return Ok(PostOrComment::Post(Box::new(p)));
399 let ap_id = apub_id.clone();
400 let comment = blocking(context.pool(), move |conn| {
401 Comment::read_from_apub_id(conn, &ap_id.into())
404 if let Ok(c) = comment {
405 return Ok(PostOrComment::Comment(Box::new(c)));
413 Comment(Box<Comment>),
415 Community(Box<Community>),
416 Person(Box<DbPerson>),
417 PrivateMessage(Box<PrivateMessage>),
420 pub async fn find_object_by_id(context: &LemmyContext, apub_id: Url) -> Result<Object, LemmyError> {
421 let ap_id = apub_id.clone();
422 if let Ok(pc) = find_post_or_comment_by_id(context, ap_id.to_owned()).await {
424 PostOrComment::Post(p) => Object::Post(Box::new(*p)),
425 PostOrComment::Comment(c) => Object::Comment(Box::new(*c)),
429 let ap_id = apub_id.clone();
430 let person = blocking(context.pool(), move |conn| {
431 DbPerson::read_from_apub_id(conn, &ap_id.into())
434 if let Ok(u) = person {
435 return Ok(Object::Person(Box::new(u)));
438 let ap_id = apub_id.clone();
439 let community = blocking(context.pool(), move |conn| {
440 Community::read_from_apub_id(conn, &ap_id.into())
443 if let Ok(c) = community {
444 return Ok(Object::Community(Box::new(c)));
447 let private_message = blocking(context.pool(), move |conn| {
448 PrivateMessage::read_from_apub_id(conn, &apub_id.into())
451 if let Ok(pm) = private_message {
452 return Ok(Object::PrivateMessage(Box::new(pm)));
458 pub async fn check_community_or_site_ban(
460 community_id: CommunityId,
462 ) -> Result<(), LemmyError> {
464 return Err(anyhow!("Person is banned from site").into());
466 let person_id = person.id;
468 move |conn: &'_ _| CommunityPersonBanView::get(conn, person_id, community_id).is_ok();
469 if blocking(pool, is_banned).await? {
470 return Err(anyhow!("Person is banned from community").into());
476 pub fn get_activity_to_and_cc<T, Kind>(activity: &T) -> Vec<Url>
480 let mut to_and_cc = vec![];
481 if let Some(to) = activity.to() {
482 let to = to.to_owned().unwrap_to_vec();
485 .map(|t| t.as_xsd_any_uri())
487 .map(|t| t.to_owned())
489 to_and_cc.append(&mut to);
491 if let Some(cc) = activity.cc() {
492 let cc = cc.to_owned().unwrap_to_vec();
495 .map(|c| c.as_xsd_any_uri())
497 .map(|c| c.to_owned())
499 to_and_cc.append(&mut cc);
504 pub async fn get_community_from_to_or_cc<T, Kind>(
506 context: &LemmyContext,
507 request_counter: &mut i32,
508 ) -> Result<Community, LemmyError>
512 for cid in get_activity_to_and_cc(activity) {
513 let community = get_or_fetch_and_upsert_community(&cid, context, request_counter).await;
514 if community.is_ok() {