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 the ActivityPub ID for a given object type and ID.
283 pub fn generate_apub_endpoint(
284 endpoint_type: EndpointType,
286 ) -> Result<DbUrl, ParseError> {
287 let point = match endpoint_type {
288 EndpointType::Community => "c",
289 EndpointType::Person => "u",
290 EndpointType::Post => "post",
291 EndpointType::Comment => "comment",
292 EndpointType::PrivateMessage => "private_message",
298 Settings::get().get_protocol_and_hostname(),
306 pub fn generate_followers_url(actor_id: &DbUrl) -> Result<DbUrl, ParseError> {
307 Ok(Url::parse(&format!("{}/followers", actor_id))?.into())
310 pub fn generate_inbox_url(actor_id: &DbUrl) -> Result<DbUrl, ParseError> {
311 Ok(Url::parse(&format!("{}/inbox", actor_id))?.into())
314 pub fn generate_shared_inbox_url(actor_id: &DbUrl) -> Result<DbUrl, LemmyError> {
315 let actor_id = actor_id.clone().into_inner();
319 &actor_id.host_str().context(location_info!())?,
320 if let Some(port) = actor_id.port() {
326 Ok(Url::parse(&url)?.into())
329 pub fn generate_moderators_url(community_id: &DbUrl) -> Result<DbUrl, LemmyError> {
330 Ok(Url::parse(&format!("{}/moderators", community_id))?.into())
333 /// Store a sent or received activity in the database, for logging purposes. These records are not
335 pub async fn insert_activity<T>(
341 ) -> Result<(), LemmyError>
343 T: Serialize + std::fmt::Debug + Send + 'static,
345 let ap_id = ap_id.to_owned().into();
346 blocking(pool, move |conn| {
347 Activity::insert(conn, ap_id, &activity, local, sensitive)
353 pub enum PostOrComment {
354 Comment(Box<Comment>),
358 /// Tries to find a post or comment in the local database, without any network requests.
359 /// This is used to handle deletions and removals, because in case we dont have the object, we can
360 /// simply ignore the activity.
361 pub async fn find_post_or_comment_by_id(
362 context: &LemmyContext,
364 ) -> Result<PostOrComment, LemmyError> {
365 let ap_id = apub_id.clone();
366 let post = blocking(context.pool(), move |conn| {
367 Post::read_from_apub_id(conn, &ap_id.into())
370 if let Ok(p) = post {
371 return Ok(PostOrComment::Post(Box::new(p)));
374 let ap_id = apub_id.clone();
375 let comment = blocking(context.pool(), move |conn| {
376 Comment::read_from_apub_id(conn, &ap_id.into())
379 if let Ok(c) = comment {
380 return Ok(PostOrComment::Comment(Box::new(c)));
388 Comment(Box<Comment>),
390 Community(Box<Community>),
391 Person(Box<DbPerson>),
392 PrivateMessage(Box<PrivateMessage>),
395 pub async fn find_object_by_id(context: &LemmyContext, apub_id: Url) -> Result<Object, LemmyError> {
396 let ap_id = apub_id.clone();
397 if let Ok(pc) = find_post_or_comment_by_id(context, ap_id.to_owned()).await {
399 PostOrComment::Post(p) => Object::Post(Box::new(*p)),
400 PostOrComment::Comment(c) => Object::Comment(Box::new(*c)),
404 let ap_id = apub_id.clone();
405 let person = blocking(context.pool(), move |conn| {
406 DbPerson::read_from_apub_id(conn, &ap_id.into())
409 if let Ok(u) = person {
410 return Ok(Object::Person(Box::new(u)));
413 let ap_id = apub_id.clone();
414 let community = blocking(context.pool(), move |conn| {
415 Community::read_from_apub_id(conn, &ap_id.into())
418 if let Ok(c) = community {
419 return Ok(Object::Community(Box::new(c)));
422 let private_message = blocking(context.pool(), move |conn| {
423 PrivateMessage::read_from_apub_id(conn, &apub_id.into())
426 if let Ok(pm) = private_message {
427 return Ok(Object::PrivateMessage(Box::new(pm)));
433 pub async fn check_community_or_site_ban(
435 community_id: CommunityId,
437 ) -> Result<(), LemmyError> {
439 return Err(anyhow!("Person is banned from site").into());
441 let person_id = person.id;
443 move |conn: &'_ _| CommunityPersonBanView::get(conn, person_id, community_id).is_ok();
444 if blocking(pool, is_banned).await? {
445 return Err(anyhow!("Person is banned from community").into());
451 pub fn get_activity_to_and_cc<T, Kind>(activity: &T) -> Vec<Url>
455 let mut to_and_cc = vec![];
456 if let Some(to) = activity.to() {
457 let to = to.to_owned().unwrap_to_vec();
460 .map(|t| t.as_xsd_any_uri())
462 .map(|t| t.to_owned())
464 to_and_cc.append(&mut to);
466 if let Some(cc) = activity.cc() {
467 let cc = cc.to_owned().unwrap_to_vec();
470 .map(|c| c.as_xsd_any_uri())
472 .map(|c| c.to_owned())
474 to_and_cc.append(&mut cc);
479 pub async fn get_community_from_to_or_cc<T, Kind>(
481 context: &LemmyContext,
482 request_counter: &mut i32,
483 ) -> Result<Community, LemmyError>
487 for cid in get_activity_to_and_cc(activity) {
488 let community = get_or_fetch_and_upsert_community(&cid, context, request_counter).await;
489 if community.is_ok() {