2 extern crate lazy_static;
5 pub mod activity_queue;
13 use crate::extensions::{
14 group_extensions::GroupExtension,
15 page_extension::PageExtension,
16 signatures::{PublicKey, PublicKeyExtension},
18 use activitystreams::{
20 actor::{ApActor, Group, Person},
22 object::{ApObject, Note, Page},
24 use activitystreams_ext::{Ext1, Ext2};
25 use anyhow::{anyhow, Context};
27 use lemmy_api_structs::blocking;
28 use lemmy_db_queries::{source::activity::Activity_, ApubObject, DbPool};
29 use lemmy_db_schema::{
35 private_message::PrivateMessage,
40 use lemmy_utils::{location_info, settings::structs::Settings, LemmyError};
41 use lemmy_websocket::LemmyContext;
44 use url::{ParseError, Url};
46 /// Activitystreams type for community
47 type GroupExt = Ext2<ApActor<ApObject<Group>>, GroupExtension, PublicKeyExtension>;
48 /// Activitystreams type for user
49 type PersonExt = Ext1<ApActor<ApObject<Person>>, PublicKeyExtension>;
50 /// Activitystreams type for post
51 type PageExt = Ext1<ApObject<Page>, PageExtension>;
52 type NoteExt = ApObject<Note>;
54 pub static APUB_JSON_CONTENT_TYPE: &str = "application/activity+json";
56 /// Checks if the ID is allowed for sending or receiving.
58 /// In particular, it checks for:
59 /// - federation being enabled (if its disabled, only local URLs are allowed)
60 /// - the correct scheme (either http or https)
61 /// - URL being in the allowlist (if it is active)
62 /// - URL not being in the blocklist (if it is active)
64 /// Note that only one of allowlist and blacklist can be enabled, not both.
65 fn check_is_apub_id_valid(apub_id: &Url) -> Result<(), LemmyError> {
66 let settings = Settings::get();
67 let domain = apub_id.domain().context(location_info!())?.to_string();
68 let local_instance = settings.get_hostname_without_port()?;
70 if !settings.federation().enabled {
71 return if domain == local_instance {
76 "Trying to connect with {}, but federation is disabled",
84 let host = apub_id.host_str().context(location_info!())?;
85 let host_as_ip = host.parse::<IpAddr>();
86 if host == "localhost" || host_as_ip.is_ok() {
87 return Err(anyhow!("invalid hostname {}: {}", host, apub_id).into());
90 if apub_id.scheme() != Settings::get().get_protocol_string() {
91 return Err(anyhow!("invalid apub id scheme {}: {}", apub_id.scheme(), apub_id).into());
94 let allowed_instances = Settings::get().get_allowed_instances();
95 let blocked_instances = Settings::get().get_blocked_instances();
97 if allowed_instances.is_none() && blocked_instances.is_none() {
99 } else if let Some(mut allowed) = allowed_instances {
100 // need to allow this explicitly because apub receive might contain objects from our local
101 // instance. split is needed to remove the port in our federation test setup.
102 allowed.push(local_instance);
104 if allowed.contains(&domain) {
107 Err(anyhow!("{} not in federation allowlist", domain).into())
109 } else if let Some(blocked) = blocked_instances {
110 if blocked.contains(&domain) {
111 Err(anyhow!("{} is in federation blocklist", domain).into())
116 panic!("Invalid config, both allowed_instances and blocked_instances are specified");
120 /// Common functions for ActivityPub objects, which are implemented by most (but not all) objects
121 /// and actors in Lemmy.
122 #[async_trait::async_trait(?Send)]
123 pub trait ApubObjectType {
124 async fn send_create(&self, creator: &User_, context: &LemmyContext) -> Result<(), LemmyError>;
125 async fn send_update(&self, creator: &User_, context: &LemmyContext) -> Result<(), LemmyError>;
126 async fn send_delete(&self, creator: &User_, context: &LemmyContext) -> Result<(), LemmyError>;
127 async fn send_undo_delete(
130 context: &LemmyContext,
131 ) -> Result<(), LemmyError>;
132 async fn send_remove(&self, mod_: &User_, context: &LemmyContext) -> Result<(), LemmyError>;
133 async fn send_undo_remove(&self, mod_: &User_, context: &LemmyContext) -> Result<(), LemmyError>;
136 #[async_trait::async_trait(?Send)]
137 pub trait ApubLikeableType {
138 async fn send_like(&self, creator: &User_, context: &LemmyContext) -> Result<(), LemmyError>;
139 async fn send_dislike(&self, creator: &User_, context: &LemmyContext) -> Result<(), LemmyError>;
140 async fn send_undo_like(&self, creator: &User_, context: &LemmyContext)
141 -> Result<(), LemmyError>;
144 /// Common methods provided by ActivityPub actors (community and user). Not all methods are
145 /// implemented by all actors.
146 #[async_trait::async_trait(?Send)]
147 pub trait ActorType {
148 fn is_local(&self) -> bool;
149 fn actor_id(&self) -> Url;
151 // TODO: every actor should have a public key, so this shouldnt be an option (needs to be fixed in db)
152 fn public_key(&self) -> Option<String>;
153 fn private_key(&self) -> Option<String>;
155 async fn send_follow(
157 follow_actor_id: &Url,
158 context: &LemmyContext,
159 ) -> Result<(), LemmyError>;
160 async fn send_unfollow(
162 follow_actor_id: &Url,
163 context: &LemmyContext,
164 ) -> Result<(), LemmyError>;
166 async fn send_accept_follow(
169 context: &LemmyContext,
170 ) -> Result<(), LemmyError>;
172 async fn send_delete(&self, context: &LemmyContext) -> Result<(), LemmyError>;
173 async fn send_undo_delete(&self, context: &LemmyContext) -> Result<(), LemmyError>;
175 async fn send_remove(&self, context: &LemmyContext) -> Result<(), LemmyError>;
176 async fn send_undo_remove(&self, context: &LemmyContext) -> Result<(), LemmyError>;
178 async fn send_announce(
181 context: &LemmyContext,
182 ) -> Result<(), LemmyError>;
184 /// For a given community, returns the inboxes of all followers.
185 async fn get_follower_inboxes(&self, pool: &DbPool) -> Result<Vec<Url>, LemmyError>;
187 fn get_shared_inbox_or_inbox_url(&self) -> Url;
189 /// Outbox URL is not generally used by Lemmy, so it can be generated on the fly (but only for
191 fn get_outbox_url(&self) -> Result<Url, LemmyError> {
192 if !self.is_local() {
193 return Err(anyhow!("get_outbox_url() called for remote actor").into());
195 Ok(Url::parse(&format!("{}/outbox", &self.actor_id()))?)
198 fn get_public_key_ext(&self) -> Result<PublicKeyExtension, LemmyError> {
201 id: format!("{}#main-key", self.actor_id()),
202 owner: self.actor_id(),
203 public_key_pem: self.public_key().context(location_info!())?,
210 pub enum EndpointType {
218 /// Generates the ActivityPub ID for a given object type and ID.
219 pub fn generate_apub_endpoint(
220 endpoint_type: EndpointType,
222 ) -> Result<DbUrl, ParseError> {
223 let point = match endpoint_type {
224 EndpointType::Community => "c",
225 EndpointType::User => "u",
226 EndpointType::Post => "post",
227 EndpointType::Comment => "comment",
228 EndpointType::PrivateMessage => "private_message",
234 Settings::get().get_protocol_and_hostname(),
242 pub fn generate_followers_url(actor_id: &DbUrl) -> Result<DbUrl, ParseError> {
243 Ok(Url::parse(&format!("{}/followers", actor_id))?.into())
246 pub fn generate_inbox_url(actor_id: &DbUrl) -> Result<DbUrl, ParseError> {
247 Ok(Url::parse(&format!("{}/inbox", actor_id))?.into())
250 pub fn generate_shared_inbox_url(actor_id: &DbUrl) -> Result<DbUrl, LemmyError> {
251 let actor_id = actor_id.clone().into_inner();
255 &actor_id.host_str().context(location_info!())?,
256 if let Some(port) = actor_id.port() {
262 Ok(Url::parse(&url)?.into())
265 pub(crate) fn generate_moderators_url(community_id: &DbUrl) -> Result<DbUrl, LemmyError> {
266 Ok(Url::parse(&format!("{}/moderators", community_id))?.into())
269 /// Store a sent or received activity in the database, for logging purposes. These records are not
271 pub(crate) async fn insert_activity<T>(
277 ) -> Result<(), LemmyError>
279 T: Serialize + std::fmt::Debug + Send + 'static,
281 let ap_id = ap_id.to_owned().into();
282 blocking(pool, move |conn| {
283 Activity::insert(conn, ap_id, &activity, local, sensitive)
289 pub(crate) enum PostOrComment {
290 Comment(Box<Comment>),
294 /// Tries to find a post or comment in the local database, without any network requests.
295 /// This is used to handle deletions and removals, because in case we dont have the object, we can
296 /// simply ignore the activity.
297 pub(crate) async fn find_post_or_comment_by_id(
298 context: &LemmyContext,
300 ) -> Result<PostOrComment, LemmyError> {
301 let ap_id = apub_id.clone();
302 let post = blocking(context.pool(), move |conn| {
303 Post::read_from_apub_id(conn, &ap_id.into())
306 if let Ok(p) = post {
307 return Ok(PostOrComment::Post(Box::new(p)));
310 let ap_id = apub_id.clone();
311 let comment = blocking(context.pool(), move |conn| {
312 Comment::read_from_apub_id(conn, &ap_id.into())
315 if let Ok(c) = comment {
316 return Ok(PostOrComment::Comment(Box::new(c)));
322 pub(crate) enum Object {
325 Community(Community),
327 PrivateMessage(PrivateMessage),
330 pub(crate) async fn find_object_by_id(
331 context: &LemmyContext,
333 ) -> Result<Object, LemmyError> {
334 let ap_id = apub_id.clone();
335 if let Ok(pc) = find_post_or_comment_by_id(context, ap_id.to_owned()).await {
337 PostOrComment::Post(p) => Object::Post(*p),
338 PostOrComment::Comment(c) => Object::Comment(*c),
342 let ap_id = apub_id.clone();
343 let user = blocking(context.pool(), move |conn| {
344 User_::read_from_apub_id(conn, &ap_id.into())
347 if let Ok(u) = user {
348 return Ok(Object::User(u));
351 let ap_id = apub_id.clone();
352 let community = blocking(context.pool(), move |conn| {
353 Community::read_from_apub_id(conn, &ap_id.into())
356 if let Ok(c) = community {
357 return Ok(Object::Community(c));
360 let private_message = blocking(context.pool(), move |conn| {
361 PrivateMessage::read_from_apub_id(conn, &apub_id.into())
364 if let Ok(pm) = private_message {
365 return Ok(Object::PrivateMessage(pm));