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_db_queries::{source::activity::Activity_, ApubObject, DbPool};
28 use lemmy_db_schema::source::{
33 private_message::PrivateMessage,
36 use lemmy_structs::blocking;
37 use lemmy_utils::{location_info, settings::Settings, LemmyError};
38 use lemmy_websocket::LemmyContext;
41 use url::{ParseError, Url};
43 /// Activitystreams type for community
44 type GroupExt = Ext2<ApActor<ApObject<Group>>, GroupExtension, PublicKeyExtension>;
45 /// Activitystreams type for user
46 type PersonExt = Ext1<ApActor<ApObject<Person>>, PublicKeyExtension>;
47 /// Activitystreams type for post
48 type PageExt = Ext1<ApObject<Page>, PageExtension>;
49 type NoteExt = ApObject<Note>;
51 pub static APUB_JSON_CONTENT_TYPE: &str = "application/activity+json";
53 /// Checks if the ID is allowed for sending or receiving.
55 /// In particular, it checks for:
56 /// - federation being enabled (if its disabled, only local URLs are allowed)
57 /// - the correct scheme (either http or https)
58 /// - URL being in the allowlist (if it is active)
59 /// - URL not being in the blocklist (if it is active)
61 /// Note that only one of allowlist and blacklist can be enabled, not both.
62 fn check_is_apub_id_valid(apub_id: &Url) -> Result<(), LemmyError> {
63 let settings = Settings::get();
64 let domain = apub_id.domain().context(location_info!())?.to_string();
65 let local_instance = settings.get_hostname_without_port()?;
67 if !settings.federation.enabled {
68 return if domain == local_instance {
73 "Trying to connect with {}, but federation is disabled",
81 let host = apub_id.host_str().context(location_info!())?;
82 let host_as_ip = host.parse::<IpAddr>();
83 if host == "localhost" || host_as_ip.is_ok() {
84 return Err(anyhow!("invalid hostname {}: {}", host, apub_id).into());
87 if apub_id.scheme() != Settings::get().get_protocol_string() {
88 return Err(anyhow!("invalid apub id scheme {}: {}", apub_id.scheme(), apub_id).into());
91 let mut allowed_instances = Settings::get().get_allowed_instances();
92 let blocked_instances = Settings::get().get_blocked_instances();
93 if allowed_instances.is_empty() && blocked_instances.is_empty() {
95 } else if !allowed_instances.is_empty() {
96 // need to allow this explicitly because apub receive might contain objects from our local
97 // instance. split is needed to remove the port in our federation test setup.
98 allowed_instances.push(local_instance);
100 if allowed_instances.contains(&domain) {
103 Err(anyhow!("{} not in federation allowlist", domain).into())
105 } else if !blocked_instances.is_empty() {
106 if blocked_instances.contains(&domain) {
107 Err(anyhow!("{} is in federation blocklist", domain).into())
112 panic!("Invalid config, both allowed_instances and blocked_instances are specified");
116 /// Common functions for ActivityPub objects, which are implemented by most (but not all) objects
117 /// and actors in Lemmy.
118 #[async_trait::async_trait(?Send)]
119 pub trait ApubObjectType {
120 async fn send_create(&self, creator: &User_, context: &LemmyContext) -> Result<(), LemmyError>;
121 async fn send_update(&self, creator: &User_, context: &LemmyContext) -> Result<(), LemmyError>;
122 async fn send_delete(&self, creator: &User_, context: &LemmyContext) -> Result<(), LemmyError>;
123 async fn send_undo_delete(
126 context: &LemmyContext,
127 ) -> Result<(), LemmyError>;
128 async fn send_remove(&self, mod_: &User_, context: &LemmyContext) -> Result<(), LemmyError>;
129 async fn send_undo_remove(&self, mod_: &User_, context: &LemmyContext) -> Result<(), LemmyError>;
132 #[async_trait::async_trait(?Send)]
133 pub trait ApubLikeableType {
134 async fn send_like(&self, creator: &User_, context: &LemmyContext) -> Result<(), LemmyError>;
135 async fn send_dislike(&self, creator: &User_, context: &LemmyContext) -> Result<(), LemmyError>;
136 async fn send_undo_like(&self, creator: &User_, context: &LemmyContext)
137 -> Result<(), LemmyError>;
140 /// Common methods provided by ActivityPub actors (community and user). Not all methods are
141 /// implemented by all actors.
142 #[async_trait::async_trait(?Send)]
143 pub trait ActorType {
144 fn is_local(&self) -> bool;
145 fn actor_id(&self) -> Url;
147 // TODO: every actor should have a public key, so this shouldnt be an option (needs to be fixed in db)
148 fn public_key(&self) -> Option<String>;
149 fn private_key(&self) -> Option<String>;
151 async fn send_follow(
153 follow_actor_id: &Url,
154 context: &LemmyContext,
155 ) -> Result<(), LemmyError>;
156 async fn send_unfollow(
158 follow_actor_id: &Url,
159 context: &LemmyContext,
160 ) -> Result<(), LemmyError>;
162 async fn send_accept_follow(
165 context: &LemmyContext,
166 ) -> Result<(), LemmyError>;
168 async fn send_delete(&self, context: &LemmyContext) -> Result<(), LemmyError>;
169 async fn send_undo_delete(&self, context: &LemmyContext) -> Result<(), LemmyError>;
171 async fn send_remove(&self, context: &LemmyContext) -> Result<(), LemmyError>;
172 async fn send_undo_remove(&self, context: &LemmyContext) -> Result<(), LemmyError>;
174 async fn send_announce(
177 context: &LemmyContext,
178 ) -> Result<(), LemmyError>;
180 /// For a given community, returns the inboxes of all followers.
181 async fn get_follower_inboxes(&self, pool: &DbPool) -> Result<Vec<Url>, LemmyError>;
183 fn get_shared_inbox_or_inbox_url(&self) -> Url;
185 /// Outbox URL is not generally used by Lemmy, so it can be generated on the fly (but only for
187 fn get_outbox_url(&self) -> Result<Url, LemmyError> {
188 if !self.is_local() {
189 return Err(anyhow!("get_outbox_url() called for remote actor").into());
191 Ok(Url::parse(&format!("{}/outbox", &self.actor_id()))?)
194 fn get_public_key_ext(&self) -> Result<PublicKeyExtension, LemmyError> {
197 id: format!("{}#main-key", self.actor_id()),
198 owner: self.actor_id(),
199 public_key_pem: self.public_key().context(location_info!())?,
206 pub enum EndpointType {
214 /// Generates the ActivityPub ID for a given object type and ID.
215 pub fn generate_apub_endpoint(
216 endpoint_type: EndpointType,
218 ) -> Result<lemmy_db_schema::Url, ParseError> {
219 let point = match endpoint_type {
220 EndpointType::Community => "c",
221 EndpointType::User => "u",
222 EndpointType::Post => "post",
223 EndpointType::Comment => "comment",
224 EndpointType::PrivateMessage => "private_message",
230 Settings::get().get_protocol_and_hostname(),
238 pub fn generate_followers_url(
239 actor_id: &lemmy_db_schema::Url,
240 ) -> Result<lemmy_db_schema::Url, ParseError> {
241 Ok(Url::parse(&format!("{}/followers", actor_id))?.into())
244 pub fn generate_inbox_url(
245 actor_id: &lemmy_db_schema::Url,
246 ) -> Result<lemmy_db_schema::Url, ParseError> {
247 Ok(Url::parse(&format!("{}/inbox", actor_id))?.into())
250 pub fn generate_shared_inbox_url(
251 actor_id: &lemmy_db_schema::Url,
252 ) -> Result<lemmy_db_schema::Url, LemmyError> {
253 let actor_id = actor_id.clone().into_inner();
257 &actor_id.host_str().context(location_info!())?,
258 if let Some(port) = actor_id.port() {
264 Ok(Url::parse(&url)?.into())
267 /// Store a sent or received activity in the database, for logging purposes. These records are not
269 pub(crate) async fn insert_activity<T>(
275 ) -> Result<(), LemmyError>
277 T: Serialize + std::fmt::Debug + Send + 'static,
279 let ap_id = ap_id.to_string();
280 blocking(pool, move |conn| {
281 Activity::insert(conn, ap_id, &activity, local, sensitive)
287 pub(crate) enum PostOrComment {
292 /// Tries to find a post or comment in the local database, without any network requests.
293 /// This is used to handle deletions and removals, because in case we dont have the object, we can
294 /// simply ignore the activity.
295 pub(crate) async fn find_post_or_comment_by_id(
296 context: &LemmyContext,
298 ) -> Result<PostOrComment, LemmyError> {
299 let ap_id = apub_id.clone();
300 let post = blocking(context.pool(), move |conn| {
301 Post::read_from_apub_id(conn, &ap_id.into())
304 if let Ok(p) = post {
305 return Ok(PostOrComment::Post(p));
308 let ap_id = apub_id.clone();
309 let comment = blocking(context.pool(), move |conn| {
310 Comment::read_from_apub_id(conn, &ap_id.into())
313 if let Ok(c) = comment {
314 return Ok(PostOrComment::Comment(c));
320 pub(crate) enum Object {
323 Community(Community),
325 PrivateMessage(PrivateMessage),
328 pub(crate) async fn find_object_by_id(
329 context: &LemmyContext,
331 ) -> Result<Object, LemmyError> {
332 let ap_id = apub_id.clone();
333 if let Ok(pc) = find_post_or_comment_by_id(context, ap_id.to_owned()).await {
335 PostOrComment::Post(p) => Object::Post(p),
336 PostOrComment::Comment(c) => Object::Comment(c),
340 let ap_id = apub_id.clone();
341 let user = blocking(context.pool(), move |conn| {
342 User_::read_from_apub_id(conn, &ap_id.into())
345 if let Ok(u) = user {
346 return Ok(Object::User(u));
349 let ap_id = apub_id.clone();
350 let community = blocking(context.pool(), move |conn| {
351 Community::read_from_apub_id(conn, &ap_id.into())
354 if let Ok(c) = community {
355 return Ok(Object::Community(c));
358 let private_message = blocking(context.pool(), move |conn| {
359 PrivateMessage::read_from_apub_id(conn, &apub_id.into())
362 if let Ok(pm) = private_message {
363 return Ok(Object::PrivateMessage(pm));