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::source::{
34 private_message::PrivateMessage,
37 use lemmy_utils::{location_info, settings::structs::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 allowed_instances = Settings::get().get_allowed_instances();
92 let blocked_instances = Settings::get().get_blocked_instances();
94 if allowed_instances.is_none() && blocked_instances.is_none() {
96 } else if let Some(mut allowed) = allowed_instances {
97 // need to allow this explicitly because apub receive might contain objects from our local
98 // instance. split is needed to remove the port in our federation test setup.
99 allowed.push(local_instance);
101 if allowed.contains(&domain) {
104 Err(anyhow!("{} not in federation allowlist", domain).into())
106 } else if let Some(blocked) = blocked_instances {
107 if blocked.contains(&domain) {
108 Err(anyhow!("{} is in federation blocklist", domain).into())
113 panic!("Invalid config, both allowed_instances and blocked_instances are specified");
117 /// Common functions for ActivityPub objects, which are implemented by most (but not all) objects
118 /// and actors in Lemmy.
119 #[async_trait::async_trait(?Send)]
120 pub trait ApubObjectType {
121 async fn send_create(&self, creator: &User_, context: &LemmyContext) -> Result<(), LemmyError>;
122 async fn send_update(&self, creator: &User_, context: &LemmyContext) -> Result<(), LemmyError>;
123 async fn send_delete(&self, creator: &User_, context: &LemmyContext) -> Result<(), LemmyError>;
124 async fn send_undo_delete(
127 context: &LemmyContext,
128 ) -> Result<(), LemmyError>;
129 async fn send_remove(&self, mod_: &User_, context: &LemmyContext) -> Result<(), LemmyError>;
130 async fn send_undo_remove(&self, mod_: &User_, context: &LemmyContext) -> Result<(), LemmyError>;
133 #[async_trait::async_trait(?Send)]
134 pub trait ApubLikeableType {
135 async fn send_like(&self, creator: &User_, context: &LemmyContext) -> Result<(), LemmyError>;
136 async fn send_dislike(&self, creator: &User_, context: &LemmyContext) -> Result<(), LemmyError>;
137 async fn send_undo_like(&self, creator: &User_, context: &LemmyContext)
138 -> Result<(), LemmyError>;
141 /// Common methods provided by ActivityPub actors (community and user). Not all methods are
142 /// implemented by all actors.
143 #[async_trait::async_trait(?Send)]
144 pub trait ActorType {
145 fn is_local(&self) -> bool;
146 fn actor_id(&self) -> Url;
148 // TODO: every actor should have a public key, so this shouldnt be an option (needs to be fixed in db)
149 fn public_key(&self) -> Option<String>;
150 fn private_key(&self) -> Option<String>;
152 async fn send_follow(
154 follow_actor_id: &Url,
155 context: &LemmyContext,
156 ) -> Result<(), LemmyError>;
157 async fn send_unfollow(
159 follow_actor_id: &Url,
160 context: &LemmyContext,
161 ) -> Result<(), LemmyError>;
163 async fn send_accept_follow(
166 context: &LemmyContext,
167 ) -> Result<(), LemmyError>;
169 async fn send_delete(&self, context: &LemmyContext) -> Result<(), LemmyError>;
170 async fn send_undo_delete(&self, context: &LemmyContext) -> Result<(), LemmyError>;
172 async fn send_remove(&self, context: &LemmyContext) -> Result<(), LemmyError>;
173 async fn send_undo_remove(&self, context: &LemmyContext) -> Result<(), LemmyError>;
175 async fn send_announce(
178 context: &LemmyContext,
179 ) -> Result<(), LemmyError>;
181 /// For a given community, returns the inboxes of all followers.
182 async fn get_follower_inboxes(&self, pool: &DbPool) -> Result<Vec<Url>, LemmyError>;
184 fn get_shared_inbox_or_inbox_url(&self) -> Url;
186 /// Outbox URL is not generally used by Lemmy, so it can be generated on the fly (but only for
188 fn get_outbox_url(&self) -> Result<Url, LemmyError> {
189 if !self.is_local() {
190 return Err(anyhow!("get_outbox_url() called for remote actor").into());
192 Ok(Url::parse(&format!("{}/outbox", &self.actor_id()))?)
195 fn get_public_key_ext(&self) -> Result<PublicKeyExtension, LemmyError> {
198 id: format!("{}#main-key", self.actor_id()),
199 owner: self.actor_id(),
200 public_key_pem: self.public_key().context(location_info!())?,
207 pub enum EndpointType {
215 /// Generates the ActivityPub ID for a given object type and ID.
216 pub fn generate_apub_endpoint(
217 endpoint_type: EndpointType,
219 ) -> Result<lemmy_db_schema::Url, ParseError> {
220 let point = match endpoint_type {
221 EndpointType::Community => "c",
222 EndpointType::User => "u",
223 EndpointType::Post => "post",
224 EndpointType::Comment => "comment",
225 EndpointType::PrivateMessage => "private_message",
231 Settings::get().get_protocol_and_hostname(),
239 pub fn generate_followers_url(
240 actor_id: &lemmy_db_schema::Url,
241 ) -> Result<lemmy_db_schema::Url, ParseError> {
242 Ok(Url::parse(&format!("{}/followers", actor_id))?.into())
245 pub fn generate_inbox_url(
246 actor_id: &lemmy_db_schema::Url,
247 ) -> Result<lemmy_db_schema::Url, ParseError> {
248 Ok(Url::parse(&format!("{}/inbox", actor_id))?.into())
251 pub fn generate_shared_inbox_url(
252 actor_id: &lemmy_db_schema::Url,
253 ) -> Result<lemmy_db_schema::Url, LemmyError> {
254 let actor_id = actor_id.clone().into_inner();
258 &actor_id.host_str().context(location_info!())?,
259 if let Some(port) = actor_id.port() {
265 Ok(Url::parse(&url)?.into())
268 /// Store a sent or received activity in the database, for logging purposes. These records are not
270 pub(crate) async fn insert_activity<T>(
276 ) -> Result<(), LemmyError>
278 T: Serialize + std::fmt::Debug + Send + 'static,
280 let ap_id = ap_id.to_string();
281 blocking(pool, move |conn| {
282 Activity::insert(conn, ap_id, &activity, local, sensitive)
288 pub(crate) enum PostOrComment {
293 /// Tries to find a post or comment in the local database, without any network requests.
294 /// This is used to handle deletions and removals, because in case we dont have the object, we can
295 /// simply ignore the activity.
296 pub(crate) async fn find_post_or_comment_by_id(
297 context: &LemmyContext,
299 ) -> Result<PostOrComment, LemmyError> {
300 let ap_id = apub_id.clone();
301 let post = blocking(context.pool(), move |conn| {
302 Post::read_from_apub_id(conn, &ap_id.into())
305 if let Ok(p) = post {
306 return Ok(PostOrComment::Post(p));
309 let ap_id = apub_id.clone();
310 let comment = blocking(context.pool(), move |conn| {
311 Comment::read_from_apub_id(conn, &ap_id.into())
314 if let Ok(c) = comment {
315 return Ok(PostOrComment::Comment(c));
321 pub(crate) enum Object {
324 Community(Community),
326 PrivateMessage(PrivateMessage),
329 pub(crate) async fn find_object_by_id(
330 context: &LemmyContext,
332 ) -> Result<Object, LemmyError> {
333 let ap_id = apub_id.clone();
334 if let Ok(pc) = find_post_or_comment_by_id(context, ap_id.to_owned()).await {
336 PostOrComment::Post(p) => Object::Post(p),
337 PostOrComment::Comment(c) => Object::Comment(c),
341 let ap_id = apub_id.clone();
342 let user = blocking(context.pool(), move |conn| {
343 User_::read_from_apub_id(conn, &ap_id.into())
346 if let Ok(u) = user {
347 return Ok(Object::User(u));
350 let ap_id = apub_id.clone();
351 let community = blocking(context.pool(), move |conn| {
352 Community::read_from_apub_id(conn, &ap_id.into())
355 if let Ok(c) = community {
356 return Ok(Object::Community(c));
359 let private_message = blocking(context.pool(), move |conn| {
360 PrivateMessage::read_from_apub_id(conn, &apub_id.into())
363 if let Ok(pm) = private_message {
364 return Ok(Object::PrivateMessage(pm));