2 extern crate lazy_static;
5 pub mod activity_queue;
12 group_extension::GroupExtension,
13 page_extension::PageExtension,
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, Page},
25 use activitystreams_ext::{Ext1, 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
53 type PersonExt = Ext2<actor::ApActor<ApObject<actor::Person>>, PersonExtension, PublicKeyExtension>;
54 /// Activitystreams type for post
55 pub type PageExt = Ext1<ApObject<Page>, PageExtension>;
56 pub type NoteExt = ApObject<Note>;
58 pub static APUB_JSON_CONTENT_TYPE: &str = "application/activity+json";
60 /// Checks if the ID is allowed for sending or receiving.
62 /// In particular, it checks for:
63 /// - federation being enabled (if its disabled, only local URLs are allowed)
64 /// - the correct scheme (either http or https)
65 /// - URL being in the allowlist (if it is active)
66 /// - URL not being in the blocklist (if it is active)
68 pub fn check_is_apub_id_valid(apub_id: &Url, use_strict_allowlist: bool) -> Result<(), LemmyError> {
69 let settings = Settings::get();
70 let domain = apub_id.domain().context(location_info!())?.to_string();
71 let local_instance = settings.get_hostname_without_port()?;
73 if !settings.federation().enabled {
74 return if domain == local_instance {
79 "Trying to connect with {}, but federation is disabled",
87 let host = apub_id.host_str().context(location_info!())?;
88 let host_as_ip = host.parse::<IpAddr>();
89 if host == "localhost" || host_as_ip.is_ok() {
90 return Err(anyhow!("invalid hostname {}: {}", host, apub_id).into());
93 if apub_id.scheme() != Settings::get().get_protocol_string() {
94 return Err(anyhow!("invalid apub id scheme {}: {}", apub_id.scheme(), apub_id).into());
97 // TODO: might be good to put the part above in one method, and below in another
98 // (which only gets called in apub::objects)
99 // -> no that doesnt make sense, we still need the code below for blocklist and strict allowlist
100 if let Some(blocked) = Settings::get().get_blocked_instances() {
101 if blocked.contains(&domain) {
102 return Err(anyhow!("{} is in federation blocklist", domain).into());
106 if let Some(mut allowed) = Settings::get().get_allowed_instances() {
107 // Only check allowlist if this is a community, or strict allowlist is enabled.
108 let strict_allowlist = Settings::get()
112 if use_strict_allowlist || strict_allowlist {
113 // need to allow this explicitly because apub receive might contain objects from our local
115 allowed.push(local_instance);
117 if !allowed.contains(&domain) {
118 return Err(anyhow!("{} not in federation allowlist", domain).into());
126 /// Common functions for ActivityPub objects, which are implemented by most (but not all) objects
127 /// and actors in Lemmy.
128 #[async_trait::async_trait(?Send)]
129 pub trait ApubObjectType {
130 async fn send_create(&self, creator: &DbPerson, context: &LemmyContext)
131 -> Result<(), LemmyError>;
132 async fn send_update(&self, creator: &DbPerson, context: &LemmyContext)
133 -> Result<(), LemmyError>;
134 async fn send_delete(&self, creator: &DbPerson, context: &LemmyContext)
135 -> Result<(), LemmyError>;
136 async fn send_undo_delete(
139 context: &LemmyContext,
140 ) -> Result<(), LemmyError>;
141 async fn send_remove(&self, mod_: &DbPerson, context: &LemmyContext) -> Result<(), LemmyError>;
142 async fn send_undo_remove(
145 context: &LemmyContext,
146 ) -> Result<(), LemmyError>;
149 #[async_trait::async_trait(?Send)]
150 pub trait ApubLikeableType {
151 async fn send_like(&self, creator: &DbPerson, context: &LemmyContext) -> Result<(), LemmyError>;
152 async fn send_dislike(
155 context: &LemmyContext,
156 ) -> Result<(), LemmyError>;
157 async fn send_undo_like(
160 context: &LemmyContext,
161 ) -> Result<(), LemmyError>;
164 /// Common methods provided by ActivityPub actors (community and person). Not all methods are
165 /// implemented by all actors.
166 #[async_trait::async_trait(?Send)]
167 pub trait ActorType {
168 fn is_local(&self) -> bool;
169 fn actor_id(&self) -> Url;
171 // TODO: every actor should have a public key, so this shouldnt be an option (needs to be fixed in db)
172 fn public_key(&self) -> Option<String>;
173 fn private_key(&self) -> Option<String>;
175 fn get_shared_inbox_or_inbox_url(&self) -> Url;
177 /// Outbox URL is not generally used by Lemmy, so it can be generated on the fly (but only for
179 fn get_outbox_url(&self) -> Result<Url, LemmyError> {
181 if !self.is_local() {
182 return Err(anyhow!("get_outbox_url() called for remote actor").into());
185 Ok(Url::parse(&format!("{}/outbox", &self.actor_id()))?)
188 fn get_public_key_ext(&self) -> Result<PublicKeyExtension, LemmyError> {
191 id: format!("{}#main-key", self.actor_id()),
192 owner: self.actor_id(),
193 public_key_pem: self.public_key().context(location_info!())?,
200 #[async_trait::async_trait(?Send)]
201 pub trait CommunityType {
202 fn followers_url(&self) -> Url;
203 async fn get_follower_inboxes(&self, pool: &DbPool) -> Result<Vec<Url>, LemmyError>;
204 async fn send_accept_follow(
207 context: &LemmyContext,
208 ) -> Result<(), LemmyError>;
210 async fn send_update(&self, mod_: Person, context: &LemmyContext) -> Result<(), LemmyError>;
211 async fn send_delete(&self, mod_: Person, context: &LemmyContext) -> Result<(), LemmyError>;
212 async fn send_undo_delete(&self, mod_: Person, context: &LemmyContext) -> Result<(), LemmyError>;
214 async fn send_remove(&self, context: &LemmyContext) -> Result<(), LemmyError>;
215 async fn send_undo_remove(&self, context: &LemmyContext) -> Result<(), LemmyError>;
217 async fn send_announce(
221 context: &LemmyContext,
222 ) -> Result<(), LemmyError>;
224 async fn send_add_mod(
228 context: &LemmyContext,
229 ) -> Result<(), LemmyError>;
230 async fn send_remove_mod(
234 context: &LemmyContext,
235 ) -> Result<(), LemmyError>;
237 async fn send_block_user(
240 blocked_user: Person,
241 context: &LemmyContext,
242 ) -> Result<(), LemmyError>;
243 async fn send_undo_block_user(
246 blocked_user: Person,
247 context: &LemmyContext,
248 ) -> Result<(), LemmyError>;
251 #[async_trait::async_trait(?Send)]
253 async fn send_follow(
255 follow_actor_id: &Url,
256 context: &LemmyContext,
257 ) -> Result<(), LemmyError>;
258 async fn send_unfollow(
260 follow_actor_id: &Url,
261 context: &LemmyContext,
262 ) -> Result<(), LemmyError>;
265 pub enum EndpointType {
273 /// Generates the ActivityPub ID for a given object type and ID.
274 pub fn generate_apub_endpoint(
275 endpoint_type: EndpointType,
277 ) -> Result<DbUrl, ParseError> {
278 let point = match endpoint_type {
279 EndpointType::Community => "c",
280 EndpointType::Person => "u",
281 EndpointType::Post => "post",
282 EndpointType::Comment => "comment",
283 EndpointType::PrivateMessage => "private_message",
289 Settings::get().get_protocol_and_hostname(),
297 pub fn generate_followers_url(actor_id: &DbUrl) -> Result<DbUrl, ParseError> {
298 Ok(Url::parse(&format!("{}/followers", actor_id))?.into())
301 pub fn generate_inbox_url(actor_id: &DbUrl) -> Result<DbUrl, ParseError> {
302 Ok(Url::parse(&format!("{}/inbox", actor_id))?.into())
305 pub fn generate_shared_inbox_url(actor_id: &DbUrl) -> Result<DbUrl, LemmyError> {
306 let actor_id = actor_id.clone().into_inner();
310 &actor_id.host_str().context(location_info!())?,
311 if let Some(port) = actor_id.port() {
317 Ok(Url::parse(&url)?.into())
320 pub fn generate_moderators_url(community_id: &DbUrl) -> Result<DbUrl, LemmyError> {
321 Ok(Url::parse(&format!("{}/moderators", community_id))?.into())
324 /// Store a sent or received activity in the database, for logging purposes. These records are not
326 pub async fn insert_activity<T>(
332 ) -> Result<(), LemmyError>
334 T: Serialize + std::fmt::Debug + Send + 'static,
336 let ap_id = ap_id.to_owned().into();
337 blocking(pool, move |conn| {
338 Activity::insert(conn, ap_id, &activity, local, sensitive)
344 pub enum PostOrComment {
345 Comment(Box<Comment>),
349 /// Tries to find a post or comment in the local database, without any network requests.
350 /// This is used to handle deletions and removals, because in case we dont have the object, we can
351 /// simply ignore the activity.
352 pub async fn find_post_or_comment_by_id(
353 context: &LemmyContext,
355 ) -> Result<PostOrComment, LemmyError> {
356 let ap_id = apub_id.clone();
357 let post = blocking(context.pool(), move |conn| {
358 Post::read_from_apub_id(conn, &ap_id.into())
361 if let Ok(p) = post {
362 return Ok(PostOrComment::Post(Box::new(p)));
365 let ap_id = apub_id.clone();
366 let comment = blocking(context.pool(), move |conn| {
367 Comment::read_from_apub_id(conn, &ap_id.into())
370 if let Ok(c) = comment {
371 return Ok(PostOrComment::Comment(Box::new(c)));
379 Comment(Box<Comment>),
381 Community(Box<Community>),
382 Person(Box<DbPerson>),
383 PrivateMessage(Box<PrivateMessage>),
386 pub async fn find_object_by_id(context: &LemmyContext, apub_id: Url) -> Result<Object, LemmyError> {
387 let ap_id = apub_id.clone();
388 if let Ok(pc) = find_post_or_comment_by_id(context, ap_id.to_owned()).await {
390 PostOrComment::Post(p) => Object::Post(Box::new(*p)),
391 PostOrComment::Comment(c) => Object::Comment(Box::new(*c)),
395 let ap_id = apub_id.clone();
396 let person = blocking(context.pool(), move |conn| {
397 DbPerson::read_from_apub_id(conn, &ap_id.into())
400 if let Ok(u) = person {
401 return Ok(Object::Person(Box::new(u)));
404 let ap_id = apub_id.clone();
405 let community = blocking(context.pool(), move |conn| {
406 Community::read_from_apub_id(conn, &ap_id.into())
409 if let Ok(c) = community {
410 return Ok(Object::Community(Box::new(c)));
413 let private_message = blocking(context.pool(), move |conn| {
414 PrivateMessage::read_from_apub_id(conn, &apub_id.into())
417 if let Ok(pm) = private_message {
418 return Ok(Object::PrivateMessage(Box::new(pm)));
424 pub async fn check_community_or_site_ban(
426 community_id: CommunityId,
428 ) -> Result<(), LemmyError> {
430 return Err(anyhow!("Person is banned from site").into());
432 let person_id = person.id;
434 move |conn: &'_ _| CommunityPersonBanView::get(conn, person_id, community_id).is_ok();
435 if blocking(pool, is_banned).await? {
436 return Err(anyhow!("Person is banned from community").into());
442 pub fn get_activity_to_and_cc<T, Kind>(activity: &T) -> Vec<Url>
446 let mut to_and_cc = vec![];
447 if let Some(to) = activity.to() {
448 let to = to.to_owned().unwrap_to_vec();
451 .map(|t| t.as_xsd_any_uri())
453 .map(|t| t.to_owned())
455 to_and_cc.append(&mut to);
457 if let Some(cc) = activity.cc() {
458 let cc = cc.to_owned().unwrap_to_vec();
461 .map(|c| c.as_xsd_any_uri())
463 .map(|c| c.to_owned())
465 to_and_cc.append(&mut cc);
470 pub async fn get_community_from_to_or_cc<T, Kind>(
472 context: &LemmyContext,
473 request_counter: &mut i32,
474 ) -> Result<Community, LemmyError>
478 for cid in get_activity_to_and_cc(activity) {
479 let community = get_or_fetch_and_upsert_community(&cid, context, request_counter).await;
480 if community.is_ok() {