2 extern crate lazy_static;
5 pub mod activity_queue;
13 group_extension::GroupExtension,
14 person_extension::PersonExtension,
15 signatures::{PublicKey, PublicKeyExtension},
17 fetcher::community::get_or_fetch_and_upsert_community,
19 use activitystreams::{
23 object::{ApObject, AsObject, Note, ObjectExt},
25 use activitystreams_ext::Ext2;
26 use anyhow::{anyhow, Context};
28 use lemmy_api_common::blocking;
29 use lemmy_db_queries::{source::activity::Activity_, ApubObject, DbPool};
30 use lemmy_db_schema::{
35 person::{Person as DbPerson, Person},
37 private_message::PrivateMessage,
42 use lemmy_db_views_actor::community_person_ban_view::CommunityPersonBanView;
43 use lemmy_utils::{location_info, settings::structs::Settings, LemmyError};
44 use lemmy_websocket::LemmyContext;
47 use url::{ParseError, Url};
49 /// Activitystreams type for community
51 Ext2<actor::ApActor<ApObject<actor::Group>>, GroupExtension, PublicKeyExtension>;
52 /// Activitystreams type for person
54 Ext2<actor::ApActor<ApObject<actor::Actor<UserTypes>>>, PersonExtension, PublicKeyExtension>;
55 pub type SiteExt = actor::ApActor<ApObject<actor::Service>>;
56 pub type NoteExt = ApObject<Note>;
58 #[derive(Clone, Copy, Debug, serde::Deserialize, serde::Serialize, PartialEq)]
64 pub static APUB_JSON_CONTENT_TYPE: &str = "application/activity+json";
66 /// Checks if the ID is allowed for sending or receiving.
68 /// In particular, it checks for:
69 /// - federation being enabled (if its disabled, only local URLs are allowed)
70 /// - the correct scheme (either http or https)
71 /// - URL being in the allowlist (if it is active)
72 /// - URL not being in the blocklist (if it is active)
74 pub fn check_is_apub_id_valid(apub_id: &Url, use_strict_allowlist: bool) -> Result<(), LemmyError> {
75 let settings = Settings::get();
76 let domain = apub_id.domain().context(location_info!())?.to_string();
77 let local_instance = settings.get_hostname_without_port()?;
79 if !settings.federation().enabled {
80 return if domain == local_instance {
85 "Trying to connect with {}, but federation is disabled",
93 let host = apub_id.host_str().context(location_info!())?;
94 let host_as_ip = host.parse::<IpAddr>();
95 if host == "localhost" || host_as_ip.is_ok() {
96 return Err(anyhow!("invalid hostname {}: {}", host, apub_id).into());
99 if apub_id.scheme() != Settings::get().get_protocol_string() {
100 return Err(anyhow!("invalid apub id scheme {}: {}", apub_id.scheme(), apub_id).into());
103 // TODO: might be good to put the part above in one method, and below in another
104 // (which only gets called in apub::objects)
105 // -> no that doesnt make sense, we still need the code below for blocklist and strict allowlist
106 if let Some(blocked) = Settings::get().get_blocked_instances() {
107 if blocked.contains(&domain) {
108 return Err(anyhow!("{} is in federation blocklist", domain).into());
112 if let Some(mut allowed) = Settings::get().get_allowed_instances() {
113 // Only check allowlist if this is a community, or strict allowlist is enabled.
114 let strict_allowlist = Settings::get()
118 if use_strict_allowlist || strict_allowlist {
119 // need to allow this explicitly because apub receive might contain objects from our local
121 allowed.push(local_instance);
123 if !allowed.contains(&domain) {
124 return Err(anyhow!("{} not in federation allowlist", domain).into());
132 /// Common functions for ActivityPub objects, which are implemented by most (but not all) objects
133 /// and actors in Lemmy.
134 #[async_trait::async_trait(?Send)]
135 pub trait ApubObjectType {
136 async fn send_create(&self, creator: &DbPerson, context: &LemmyContext)
137 -> Result<(), LemmyError>;
138 async fn send_update(&self, creator: &DbPerson, context: &LemmyContext)
139 -> Result<(), LemmyError>;
140 async fn send_delete(&self, creator: &DbPerson, context: &LemmyContext)
141 -> Result<(), LemmyError>;
142 async fn send_undo_delete(
145 context: &LemmyContext,
146 ) -> Result<(), LemmyError>;
147 async fn send_remove(&self, mod_: &DbPerson, context: &LemmyContext) -> Result<(), LemmyError>;
148 async fn send_undo_remove(
151 context: &LemmyContext,
152 ) -> Result<(), LemmyError>;
155 #[async_trait::async_trait(?Send)]
156 pub trait ApubLikeableType {
157 async fn send_like(&self, creator: &DbPerson, context: &LemmyContext) -> Result<(), LemmyError>;
158 async fn send_dislike(
161 context: &LemmyContext,
162 ) -> Result<(), LemmyError>;
163 async fn send_undo_like(
166 context: &LemmyContext,
167 ) -> Result<(), LemmyError>;
170 /// Common methods provided by ActivityPub actors (community and person). Not all methods are
171 /// implemented by all actors.
172 pub trait ActorType {
173 fn is_local(&self) -> bool;
174 fn actor_id(&self) -> Url;
175 fn name(&self) -> String;
177 // TODO: every actor should have a public key, so this shouldnt be an option (needs to be fixed in db)
178 fn public_key(&self) -> Option<String>;
179 fn private_key(&self) -> Option<String>;
181 fn get_shared_inbox_or_inbox_url(&self) -> Url;
183 /// Outbox URL is not generally used by Lemmy, so it can be generated on the fly (but only for
185 fn get_outbox_url(&self) -> Result<Url, LemmyError> {
187 if !self.is_local() {
188 return Err(anyhow!("get_outbox_url() called for remote actor").into());
191 Ok(Url::parse(&format!("{}/outbox", &self.actor_id()))?)
194 fn get_public_key_ext(&self) -> Result<PublicKeyExtension, LemmyError> {
197 id: format!("{}#main-key", self.actor_id()),
198 owner: self.actor_id(),
199 public_key_pem: self.public_key().context(location_info!())?,
206 #[async_trait::async_trait(?Send)]
207 pub trait CommunityType {
208 fn followers_url(&self) -> Url;
209 async fn get_follower_inboxes(&self, pool: &DbPool) -> Result<Vec<Url>, LemmyError>;
210 async fn send_accept_follow(
213 context: &LemmyContext,
214 ) -> Result<(), LemmyError>;
216 async fn send_update(&self, mod_: Person, context: &LemmyContext) -> Result<(), LemmyError>;
217 async fn send_delete(&self, mod_: Person, context: &LemmyContext) -> Result<(), LemmyError>;
218 async fn send_undo_delete(&self, mod_: Person, context: &LemmyContext) -> Result<(), LemmyError>;
220 async fn send_remove(&self, context: &LemmyContext) -> Result<(), LemmyError>;
221 async fn send_undo_remove(&self, context: &LemmyContext) -> Result<(), LemmyError>;
223 async fn send_announce(
227 context: &LemmyContext,
228 ) -> Result<(), LemmyError>;
230 async fn send_add_mod(
234 context: &LemmyContext,
235 ) -> Result<(), LemmyError>;
236 async fn send_remove_mod(
240 context: &LemmyContext,
241 ) -> Result<(), LemmyError>;
243 async fn send_block_user(
246 blocked_user: Person,
247 context: &LemmyContext,
248 ) -> Result<(), LemmyError>;
249 async fn send_undo_block_user(
252 blocked_user: Person,
253 context: &LemmyContext,
254 ) -> Result<(), LemmyError>;
257 #[async_trait::async_trait(?Send)]
259 async fn send_follow(
261 follow_actor_id: &Url,
262 context: &LemmyContext,
263 ) -> Result<(), LemmyError>;
264 async fn send_unfollow(
266 follow_actor_id: &Url,
267 context: &LemmyContext,
268 ) -> Result<(), LemmyError>;
271 pub enum EndpointType {
279 /// Generates an apub endpoint for a given domain, IE xyz.tld
280 pub fn generate_apub_endpoint_for_domain(
281 endpoint_type: EndpointType,
284 ) -> Result<DbUrl, ParseError> {
285 let point = match endpoint_type {
286 EndpointType::Community => "c",
287 EndpointType::Person => "u",
288 EndpointType::Post => "post",
289 EndpointType::Comment => "comment",
290 EndpointType::PrivateMessage => "private_message",
293 Ok(Url::parse(&format!("{}/{}/{}", domain, point, name))?.into())
296 /// Generates the ActivityPub ID for a given object type and ID.
297 pub fn generate_apub_endpoint(
298 endpoint_type: EndpointType,
300 ) -> Result<DbUrl, ParseError> {
301 generate_apub_endpoint_for_domain(
304 &Settings::get().get_protocol_and_hostname(),
308 pub fn generate_followers_url(actor_id: &DbUrl) -> Result<DbUrl, ParseError> {
309 Ok(Url::parse(&format!("{}/followers", actor_id))?.into())
312 pub fn generate_inbox_url(actor_id: &DbUrl) -> Result<DbUrl, ParseError> {
313 Ok(Url::parse(&format!("{}/inbox", actor_id))?.into())
316 pub fn generate_shared_inbox_url(actor_id: &DbUrl) -> Result<DbUrl, LemmyError> {
317 let actor_id = actor_id.clone().into_inner();
321 &actor_id.host_str().context(location_info!())?,
322 if let Some(port) = actor_id.port() {
328 Ok(Url::parse(&url)?.into())
331 pub fn generate_moderators_url(community_id: &DbUrl) -> Result<DbUrl, LemmyError> {
332 Ok(Url::parse(&format!("{}/moderators", community_id))?.into())
335 /// Takes in a shortname of the type dessalines@xyz.tld or dessalines (assumed to be local), and outputs the actor id.
336 /// Used in the API for communities and users.
337 pub fn build_actor_id_from_shortname(
338 endpoint_type: EndpointType,
340 ) -> Result<DbUrl, ParseError> {
341 let split = short_name.split('@').collect::<Vec<&str>>();
345 // If there's no @, its local
346 let domain = if split.len() == 1 {
347 Settings::get().get_protocol_and_hostname()
349 format!("{}://{}", Settings::get().get_protocol_string(), split[1])
352 generate_apub_endpoint_for_domain(endpoint_type, name, &domain)
355 /// Store a sent or received activity in the database, for logging purposes. These records are not
357 pub async fn insert_activity<T>(
363 ) -> Result<(), LemmyError>
365 T: Serialize + std::fmt::Debug + Send + 'static,
367 let ap_id = ap_id.to_owned().into();
368 blocking(pool, move |conn| {
369 Activity::insert(conn, ap_id, &activity, local, sensitive)
375 pub enum PostOrComment {
376 Comment(Box<Comment>),
380 /// Tries to find a post or comment in the local database, without any network requests.
381 /// This is used to handle deletions and removals, because in case we dont have the object, we can
382 /// simply ignore the activity.
383 pub async fn find_post_or_comment_by_id(
384 context: &LemmyContext,
386 ) -> Result<PostOrComment, LemmyError> {
387 let ap_id = apub_id.clone();
388 let post = blocking(context.pool(), move |conn| {
389 Post::read_from_apub_id(conn, &ap_id.into())
392 if let Ok(p) = post {
393 return Ok(PostOrComment::Post(Box::new(p)));
396 let ap_id = apub_id.clone();
397 let comment = blocking(context.pool(), move |conn| {
398 Comment::read_from_apub_id(conn, &ap_id.into())
401 if let Ok(c) = comment {
402 return Ok(PostOrComment::Comment(Box::new(c)));
410 Comment(Box<Comment>),
412 Community(Box<Community>),
413 Person(Box<DbPerson>),
414 PrivateMessage(Box<PrivateMessage>),
417 pub async fn find_object_by_id(context: &LemmyContext, apub_id: Url) -> Result<Object, LemmyError> {
418 let ap_id = apub_id.clone();
419 if let Ok(pc) = find_post_or_comment_by_id(context, ap_id.to_owned()).await {
421 PostOrComment::Post(p) => Object::Post(Box::new(*p)),
422 PostOrComment::Comment(c) => Object::Comment(Box::new(*c)),
426 let ap_id = apub_id.clone();
427 let person = blocking(context.pool(), move |conn| {
428 DbPerson::read_from_apub_id(conn, &ap_id.into())
431 if let Ok(u) = person {
432 return Ok(Object::Person(Box::new(u)));
435 let ap_id = apub_id.clone();
436 let community = blocking(context.pool(), move |conn| {
437 Community::read_from_apub_id(conn, &ap_id.into())
440 if let Ok(c) = community {
441 return Ok(Object::Community(Box::new(c)));
444 let private_message = blocking(context.pool(), move |conn| {
445 PrivateMessage::read_from_apub_id(conn, &apub_id.into())
448 if let Ok(pm) = private_message {
449 return Ok(Object::PrivateMessage(Box::new(pm)));
455 pub async fn check_community_or_site_ban(
457 community_id: CommunityId,
459 ) -> Result<(), LemmyError> {
461 return Err(anyhow!("Person is banned from site").into());
463 let person_id = person.id;
465 move |conn: &'_ _| CommunityPersonBanView::get(conn, person_id, community_id).is_ok();
466 if blocking(pool, is_banned).await? {
467 return Err(anyhow!("Person is banned from community").into());
473 pub fn get_activity_to_and_cc<T, Kind>(activity: &T) -> Vec<Url>
477 let mut to_and_cc = vec![];
478 if let Some(to) = activity.to() {
479 let to = to.to_owned().unwrap_to_vec();
482 .map(|t| t.as_xsd_any_uri())
484 .map(|t| t.to_owned())
486 to_and_cc.append(&mut to);
488 if let Some(cc) = activity.cc() {
489 let cc = cc.to_owned().unwrap_to_vec();
492 .map(|c| c.as_xsd_any_uri())
494 .map(|c| c.to_owned())
496 to_and_cc.append(&mut cc);
501 pub async fn get_community_from_to_or_cc<T, Kind>(
503 context: &LemmyContext,
504 request_counter: &mut i32,
505 ) -> Result<Community, LemmyError>
509 for cid in get_activity_to_and_cc(activity) {
510 let community = get_or_fetch_and_upsert_community(&cid, context, request_counter).await;
511 if community.is_ok() {