2 extern crate lazy_static;
5 pub mod activity_queue;
13 use crate::extensions::{
14 group_extension::GroupExtension,
15 page_extension::PageExtension,
16 person_extension::PersonExtension,
17 signatures::{PublicKey, PublicKeyExtension},
19 use activitystreams::{
23 object::{ApObject, Note, Page},
25 use activitystreams_ext::{Ext1, Ext2};
26 use anyhow::{anyhow, Context};
28 use lemmy_api_structs::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,
41 use lemmy_utils::{location_info, settings::structs::Settings, LemmyError};
42 use lemmy_websocket::LemmyContext;
45 use url::{ParseError, Url};
47 /// Activitystreams type for community
48 type GroupExt = Ext2<actor::ApActor<ApObject<actor::Group>>, GroupExtension, PublicKeyExtension>;
49 /// Activitystreams type for person
50 type PersonExt = Ext2<actor::ApActor<ApObject<actor::Person>>, PersonExtension, PublicKeyExtension>;
51 /// Activitystreams type for post
52 type PageExt = Ext1<ApObject<Page>, PageExtension>;
53 type NoteExt = ApObject<Note>;
55 pub static APUB_JSON_CONTENT_TYPE: &str = "application/activity+json";
57 /// Checks if the ID is allowed for sending or receiving.
59 /// In particular, it checks for:
60 /// - federation being enabled (if its disabled, only local URLs are allowed)
61 /// - the correct scheme (either http or https)
62 /// - URL being in the allowlist (if it is active)
63 /// - URL not being in the blocklist (if it is active)
65 /// Note that only one of allowlist and blacklist can be enabled, not both.
66 fn check_is_apub_id_valid(apub_id: &Url) -> Result<(), LemmyError> {
67 let settings = Settings::get();
68 let domain = apub_id.domain().context(location_info!())?.to_string();
69 let local_instance = settings.get_hostname_without_port()?;
71 if !settings.federation().enabled {
72 return if domain == local_instance {
77 "Trying to connect with {}, but federation is disabled",
85 let host = apub_id.host_str().context(location_info!())?;
86 let host_as_ip = host.parse::<IpAddr>();
87 if host == "localhost" || host_as_ip.is_ok() {
88 return Err(anyhow!("invalid hostname {}: {}", host, apub_id).into());
91 if apub_id.scheme() != Settings::get().get_protocol_string() {
92 return Err(anyhow!("invalid apub id scheme {}: {}", apub_id.scheme(), apub_id).into());
95 let allowed_instances = Settings::get().get_allowed_instances();
96 let blocked_instances = Settings::get().get_blocked_instances();
98 if allowed_instances.is_none() && blocked_instances.is_none() {
100 } else if let Some(mut allowed) = allowed_instances {
101 // need to allow this explicitly because apub receive might contain objects from our local
102 // instance. split is needed to remove the port in our federation test setup.
103 allowed.push(local_instance);
105 if allowed.contains(&domain) {
108 Err(anyhow!("{} not in federation allowlist", domain).into())
110 } else if let Some(blocked) = blocked_instances {
111 if blocked.contains(&domain) {
112 Err(anyhow!("{} is in federation blocklist", domain).into())
117 panic!("Invalid config, both allowed_instances and blocked_instances are specified");
121 /// Common functions for ActivityPub objects, which are implemented by most (but not all) objects
122 /// and actors in Lemmy.
123 #[async_trait::async_trait(?Send)]
124 pub trait ApubObjectType {
125 async fn send_create(&self, creator: &DbPerson, context: &LemmyContext)
126 -> Result<(), LemmyError>;
127 async fn send_update(&self, creator: &DbPerson, context: &LemmyContext)
128 -> Result<(), LemmyError>;
129 async fn send_delete(&self, creator: &DbPerson, context: &LemmyContext)
130 -> Result<(), LemmyError>;
131 async fn send_undo_delete(
134 context: &LemmyContext,
135 ) -> Result<(), LemmyError>;
136 async fn send_remove(&self, mod_: &DbPerson, context: &LemmyContext) -> Result<(), LemmyError>;
137 async fn send_undo_remove(
140 context: &LemmyContext,
141 ) -> Result<(), LemmyError>;
144 #[async_trait::async_trait(?Send)]
145 pub trait ApubLikeableType {
146 async fn send_like(&self, creator: &DbPerson, context: &LemmyContext) -> Result<(), LemmyError>;
147 async fn send_dislike(
150 context: &LemmyContext,
151 ) -> Result<(), LemmyError>;
152 async fn send_undo_like(
155 context: &LemmyContext,
156 ) -> Result<(), LemmyError>;
159 /// Common methods provided by ActivityPub actors (community and person). Not all methods are
160 /// implemented by all actors.
161 #[async_trait::async_trait(?Send)]
162 pub trait ActorType {
163 fn is_local(&self) -> bool;
164 fn actor_id(&self) -> Url;
166 // TODO: every actor should have a public key, so this shouldnt be an option (needs to be fixed in db)
167 fn public_key(&self) -> Option<String>;
168 fn private_key(&self) -> Option<String>;
170 fn get_shared_inbox_or_inbox_url(&self) -> Url;
172 /// Outbox URL is not generally used by Lemmy, so it can be generated on the fly (but only for
174 fn get_outbox_url(&self) -> Result<Url, LemmyError> {
175 if !self.is_local() {
176 return Err(anyhow!("get_outbox_url() called for remote actor").into());
178 Ok(Url::parse(&format!("{}/outbox", &self.actor_id()))?)
181 fn get_public_key_ext(&self) -> Result<PublicKeyExtension, LemmyError> {
184 id: format!("{}#main-key", self.actor_id()),
185 owner: self.actor_id(),
186 public_key_pem: self.public_key().context(location_info!())?,
193 #[async_trait::async_trait(?Send)]
194 pub trait CommunityType {
195 async fn get_follower_inboxes(&self, pool: &DbPool) -> Result<Vec<Url>, LemmyError>;
196 async fn send_accept_follow(
199 context: &LemmyContext,
200 ) -> Result<(), LemmyError>;
202 async fn send_delete(&self, context: &LemmyContext) -> Result<(), LemmyError>;
203 async fn send_undo_delete(&self, context: &LemmyContext) -> Result<(), LemmyError>;
205 async fn send_remove(&self, context: &LemmyContext) -> Result<(), LemmyError>;
206 async fn send_undo_remove(&self, context: &LemmyContext) -> Result<(), LemmyError>;
208 async fn send_announce(
211 context: &LemmyContext,
212 ) -> Result<(), LemmyError>;
214 async fn send_add_mod(
218 context: &LemmyContext,
219 ) -> Result<(), LemmyError>;
220 async fn send_remove_mod(
224 context: &LemmyContext,
225 ) -> Result<(), LemmyError>;
228 #[async_trait::async_trait(?Send)]
230 async fn send_follow(
232 follow_actor_id: &Url,
233 context: &LemmyContext,
234 ) -> Result<(), LemmyError>;
235 async fn send_unfollow(
237 follow_actor_id: &Url,
238 context: &LemmyContext,
239 ) -> Result<(), LemmyError>;
242 pub enum EndpointType {
250 /// Generates the ActivityPub ID for a given object type and ID.
251 pub fn generate_apub_endpoint(
252 endpoint_type: EndpointType,
254 ) -> Result<DbUrl, ParseError> {
255 let point = match endpoint_type {
256 EndpointType::Community => "c",
257 EndpointType::Person => "u",
258 EndpointType::Post => "post",
259 EndpointType::Comment => "comment",
260 EndpointType::PrivateMessage => "private_message",
266 Settings::get().get_protocol_and_hostname(),
274 pub fn generate_followers_url(actor_id: &DbUrl) -> Result<DbUrl, ParseError> {
275 Ok(Url::parse(&format!("{}/followers", actor_id))?.into())
278 pub fn generate_inbox_url(actor_id: &DbUrl) -> Result<DbUrl, ParseError> {
279 Ok(Url::parse(&format!("{}/inbox", actor_id))?.into())
282 pub fn generate_shared_inbox_url(actor_id: &DbUrl) -> Result<DbUrl, LemmyError> {
283 let actor_id = actor_id.clone().into_inner();
287 &actor_id.host_str().context(location_info!())?,
288 if let Some(port) = actor_id.port() {
294 Ok(Url::parse(&url)?.into())
297 pub(crate) fn generate_moderators_url(community_id: &DbUrl) -> Result<DbUrl, LemmyError> {
298 Ok(Url::parse(&format!("{}/moderators", community_id))?.into())
301 /// Store a sent or received activity in the database, for logging purposes. These records are not
303 pub(crate) async fn insert_activity<T>(
309 ) -> Result<(), LemmyError>
311 T: Serialize + std::fmt::Debug + Send + 'static,
313 let ap_id = ap_id.to_owned().into();
314 blocking(pool, move |conn| {
315 Activity::insert(conn, ap_id, &activity, local, sensitive)
321 pub(crate) enum PostOrComment {
322 Comment(Box<Comment>),
326 /// Tries to find a post or comment in the local database, without any network requests.
327 /// This is used to handle deletions and removals, because in case we dont have the object, we can
328 /// simply ignore the activity.
329 pub(crate) async fn find_post_or_comment_by_id(
330 context: &LemmyContext,
332 ) -> Result<PostOrComment, LemmyError> {
333 let ap_id = apub_id.clone();
334 let post = blocking(context.pool(), move |conn| {
335 Post::read_from_apub_id(conn, &ap_id.into())
338 if let Ok(p) = post {
339 return Ok(PostOrComment::Post(Box::new(p)));
342 let ap_id = apub_id.clone();
343 let comment = blocking(context.pool(), move |conn| {
344 Comment::read_from_apub_id(conn, &ap_id.into())
347 if let Ok(c) = comment {
348 return Ok(PostOrComment::Comment(Box::new(c)));
355 pub(crate) enum Object {
356 Comment(Box<Comment>),
358 Community(Box<Community>),
359 Person(Box<DbPerson>),
360 PrivateMessage(Box<PrivateMessage>),
363 pub(crate) async fn find_object_by_id(
364 context: &LemmyContext,
366 ) -> Result<Object, LemmyError> {
367 let ap_id = apub_id.clone();
368 if let Ok(pc) = find_post_or_comment_by_id(context, ap_id.to_owned()).await {
370 PostOrComment::Post(p) => Object::Post(Box::new(*p)),
371 PostOrComment::Comment(c) => Object::Comment(Box::new(*c)),
375 let ap_id = apub_id.clone();
376 let person = blocking(context.pool(), move |conn| {
377 DbPerson::read_from_apub_id(conn, &ap_id.into())
380 if let Ok(u) = person {
381 return Ok(Object::Person(Box::new(u)));
384 let ap_id = apub_id.clone();
385 let community = blocking(context.pool(), move |conn| {
386 Community::read_from_apub_id(conn, &ap_id.into())
389 if let Ok(c) = community {
390 return Ok(Object::Community(Box::new(c)));
393 let private_message = blocking(context.pool(), move |conn| {
394 PrivateMessage::read_from_apub_id(conn, &apub_id.into())
397 if let Ok(pm) = private_message {
398 return Ok(Object::PrivateMessage(Box::new(pm)));