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 /// Note that only one of allowlist and blacklist can be enabled, not both.
69 pub fn check_is_apub_id_valid(apub_id: &Url) -> Result<(), LemmyError> {
70 let settings = Settings::get();
71 let domain = apub_id.domain().context(location_info!())?.to_string();
72 let local_instance = settings.get_hostname_without_port()?;
74 if !settings.federation().enabled {
75 return if domain == local_instance {
80 "Trying to connect with {}, but federation is disabled",
88 let host = apub_id.host_str().context(location_info!())?;
89 let host_as_ip = host.parse::<IpAddr>();
90 if host == "localhost" || host_as_ip.is_ok() {
91 return Err(anyhow!("invalid hostname {}: {}", host, apub_id).into());
94 if apub_id.scheme() != Settings::get().get_protocol_string() {
95 return Err(anyhow!("invalid apub id scheme {}: {}", apub_id.scheme(), apub_id).into());
98 let allowed_instances = Settings::get().get_allowed_instances();
99 let blocked_instances = Settings::get().get_blocked_instances();
101 if allowed_instances.is_none() && blocked_instances.is_none() {
103 } else if let Some(mut allowed) = allowed_instances {
104 // need to allow this explicitly because apub receive might contain objects from our local
105 // instance. split is needed to remove the port in our federation test setup.
106 allowed.push(local_instance);
108 if allowed.contains(&domain) {
111 Err(anyhow!("{} not in federation allowlist", domain).into())
113 } else if let Some(blocked) = blocked_instances {
114 if blocked.contains(&domain) {
115 Err(anyhow!("{} is in federation blocklist", domain).into())
120 panic!("Invalid config, both allowed_instances and blocked_instances are specified");
124 /// Common functions for ActivityPub objects, which are implemented by most (but not all) objects
125 /// and actors in Lemmy.
126 #[async_trait::async_trait(?Send)]
127 pub trait ApubObjectType {
128 async fn send_create(&self, creator: &DbPerson, context: &LemmyContext)
129 -> Result<(), LemmyError>;
130 async fn send_update(&self, creator: &DbPerson, context: &LemmyContext)
131 -> Result<(), LemmyError>;
132 async fn send_delete(&self, creator: &DbPerson, context: &LemmyContext)
133 -> Result<(), LemmyError>;
134 async fn send_undo_delete(
137 context: &LemmyContext,
138 ) -> Result<(), LemmyError>;
139 async fn send_remove(&self, mod_: &DbPerson, context: &LemmyContext) -> Result<(), LemmyError>;
140 async fn send_undo_remove(
143 context: &LemmyContext,
144 ) -> Result<(), LemmyError>;
147 #[async_trait::async_trait(?Send)]
148 pub trait ApubLikeableType {
149 async fn send_like(&self, creator: &DbPerson, context: &LemmyContext) -> Result<(), LemmyError>;
150 async fn send_dislike(
153 context: &LemmyContext,
154 ) -> Result<(), LemmyError>;
155 async fn send_undo_like(
158 context: &LemmyContext,
159 ) -> Result<(), LemmyError>;
162 /// Common methods provided by ActivityPub actors (community and person). Not all methods are
163 /// implemented by all actors.
164 #[async_trait::async_trait(?Send)]
165 pub trait ActorType {
166 fn is_local(&self) -> bool;
167 fn actor_id(&self) -> Url;
169 // TODO: every actor should have a public key, so this shouldnt be an option (needs to be fixed in db)
170 fn public_key(&self) -> Option<String>;
171 fn private_key(&self) -> Option<String>;
173 fn get_shared_inbox_or_inbox_url(&self) -> Url;
175 /// Outbox URL is not generally used by Lemmy, so it can be generated on the fly (but only for
177 fn get_outbox_url(&self) -> Result<Url, LemmyError> {
179 if !self.is_local() {
180 return Err(anyhow!("get_outbox_url() called for remote actor").into());
183 Ok(Url::parse(&format!("{}/outbox", &self.actor_id()))?)
186 fn get_public_key_ext(&self) -> Result<PublicKeyExtension, LemmyError> {
189 id: format!("{}#main-key", self.actor_id()),
190 owner: self.actor_id(),
191 public_key_pem: self.public_key().context(location_info!())?,
198 #[async_trait::async_trait(?Send)]
199 pub trait CommunityType {
200 fn followers_url(&self) -> Url;
201 async fn get_follower_inboxes(&self, pool: &DbPool) -> Result<Vec<Url>, LemmyError>;
202 async fn send_accept_follow(
205 context: &LemmyContext,
206 ) -> Result<(), LemmyError>;
208 async fn send_update(&self, mod_: Person, context: &LemmyContext) -> Result<(), LemmyError>;
209 async fn send_delete(&self, mod_: Person, context: &LemmyContext) -> Result<(), LemmyError>;
210 async fn send_undo_delete(&self, mod_: Person, context: &LemmyContext) -> Result<(), LemmyError>;
212 async fn send_remove(&self, context: &LemmyContext) -> Result<(), LemmyError>;
213 async fn send_undo_remove(&self, context: &LemmyContext) -> Result<(), LemmyError>;
215 async fn send_announce(
219 context: &LemmyContext,
220 ) -> Result<(), LemmyError>;
222 async fn send_add_mod(
226 context: &LemmyContext,
227 ) -> Result<(), LemmyError>;
228 async fn send_remove_mod(
232 context: &LemmyContext,
233 ) -> Result<(), LemmyError>;
235 async fn send_block_user(
238 blocked_user: Person,
239 context: &LemmyContext,
240 ) -> Result<(), LemmyError>;
241 async fn send_undo_block_user(
244 blocked_user: Person,
245 context: &LemmyContext,
246 ) -> Result<(), LemmyError>;
249 #[async_trait::async_trait(?Send)]
251 async fn send_follow(
253 follow_actor_id: &Url,
254 context: &LemmyContext,
255 ) -> Result<(), LemmyError>;
256 async fn send_unfollow(
258 follow_actor_id: &Url,
259 context: &LemmyContext,
260 ) -> Result<(), LemmyError>;
263 pub enum EndpointType {
271 /// Generates the ActivityPub ID for a given object type and ID.
272 pub fn generate_apub_endpoint(
273 endpoint_type: EndpointType,
275 ) -> Result<DbUrl, ParseError> {
276 let point = match endpoint_type {
277 EndpointType::Community => "c",
278 EndpointType::Person => "u",
279 EndpointType::Post => "post",
280 EndpointType::Comment => "comment",
281 EndpointType::PrivateMessage => "private_message",
287 Settings::get().get_protocol_and_hostname(),
295 pub fn generate_followers_url(actor_id: &DbUrl) -> Result<DbUrl, ParseError> {
296 Ok(Url::parse(&format!("{}/followers", actor_id))?.into())
299 pub fn generate_inbox_url(actor_id: &DbUrl) -> Result<DbUrl, ParseError> {
300 Ok(Url::parse(&format!("{}/inbox", actor_id))?.into())
303 pub fn generate_shared_inbox_url(actor_id: &DbUrl) -> Result<DbUrl, LemmyError> {
304 let actor_id = actor_id.clone().into_inner();
308 &actor_id.host_str().context(location_info!())?,
309 if let Some(port) = actor_id.port() {
315 Ok(Url::parse(&url)?.into())
318 pub fn generate_moderators_url(community_id: &DbUrl) -> Result<DbUrl, LemmyError> {
319 Ok(Url::parse(&format!("{}/moderators", community_id))?.into())
322 /// Store a sent or received activity in the database, for logging purposes. These records are not
324 pub async fn insert_activity<T>(
330 ) -> Result<(), LemmyError>
332 T: Serialize + std::fmt::Debug + Send + 'static,
334 let ap_id = ap_id.to_owned().into();
335 blocking(pool, move |conn| {
336 Activity::insert(conn, ap_id, &activity, local, sensitive)
342 pub enum PostOrComment {
343 Comment(Box<Comment>),
347 /// Tries to find a post or comment in the local database, without any network requests.
348 /// This is used to handle deletions and removals, because in case we dont have the object, we can
349 /// simply ignore the activity.
350 pub async fn find_post_or_comment_by_id(
351 context: &LemmyContext,
353 ) -> Result<PostOrComment, LemmyError> {
354 let ap_id = apub_id.clone();
355 let post = blocking(context.pool(), move |conn| {
356 Post::read_from_apub_id(conn, &ap_id.into())
359 if let Ok(p) = post {
360 return Ok(PostOrComment::Post(Box::new(p)));
363 let ap_id = apub_id.clone();
364 let comment = blocking(context.pool(), move |conn| {
365 Comment::read_from_apub_id(conn, &ap_id.into())
368 if let Ok(c) = comment {
369 return Ok(PostOrComment::Comment(Box::new(c)));
377 Comment(Box<Comment>),
379 Community(Box<Community>),
380 Person(Box<DbPerson>),
381 PrivateMessage(Box<PrivateMessage>),
384 pub async fn find_object_by_id(context: &LemmyContext, apub_id: Url) -> Result<Object, LemmyError> {
385 let ap_id = apub_id.clone();
386 if let Ok(pc) = find_post_or_comment_by_id(context, ap_id.to_owned()).await {
388 PostOrComment::Post(p) => Object::Post(Box::new(*p)),
389 PostOrComment::Comment(c) => Object::Comment(Box::new(*c)),
393 let ap_id = apub_id.clone();
394 let person = blocking(context.pool(), move |conn| {
395 DbPerson::read_from_apub_id(conn, &ap_id.into())
398 if let Ok(u) = person {
399 return Ok(Object::Person(Box::new(u)));
402 let ap_id = apub_id.clone();
403 let community = blocking(context.pool(), move |conn| {
404 Community::read_from_apub_id(conn, &ap_id.into())
407 if let Ok(c) = community {
408 return Ok(Object::Community(Box::new(c)));
411 let private_message = blocking(context.pool(), move |conn| {
412 PrivateMessage::read_from_apub_id(conn, &apub_id.into())
415 if let Ok(pm) = private_message {
416 return Ok(Object::PrivateMessage(Box::new(pm)));
422 pub async fn check_community_or_site_ban(
424 community_id: CommunityId,
426 ) -> Result<(), LemmyError> {
428 return Err(anyhow!("Person is banned from site").into());
430 let person_id = person.id;
432 move |conn: &'_ _| CommunityPersonBanView::get(conn, person_id, community_id).is_ok();
433 if blocking(pool, is_banned).await? {
434 return Err(anyhow!("Person is banned from community").into());
440 pub fn get_activity_to_and_cc<T, Kind>(activity: &T) -> Vec<Url>
444 let mut to_and_cc = vec![];
445 if let Some(to) = activity.to() {
446 let to = to.to_owned().unwrap_to_vec();
449 .map(|t| t.as_xsd_any_uri())
451 .map(|t| t.to_owned())
453 to_and_cc.append(&mut to);
455 if let Some(cc) = activity.cc() {
456 let cc = cc.to_owned().unwrap_to_vec();
459 .map(|c| c.as_xsd_any_uri())
461 .map(|c| c.to_owned())
463 to_and_cc.append(&mut cc);
468 pub async fn get_community_from_to_or_cc<T, Kind>(
470 context: &LemmyContext,
471 request_counter: &mut i32,
472 ) -> Result<Community, LemmyError>
476 for cid in get_activity_to_and_cc(activity) {
477 let community = get_or_fetch_and_upsert_community(&cid, context, request_counter).await;
478 if community.is_ok() {