2 extern crate lazy_static;
5 pub mod activity_queue;
12 use crate::extensions::{
13 group_extensions::GroupExtension,
14 page_extension::PageExtension,
15 signatures::{PublicKey, PublicKeyExtension},
17 use activitystreams::{
19 actor::{ApActor, Group, Person},
21 object::{ApObject, Note, Page},
23 use activitystreams_ext::{Ext1, Ext2};
24 use anyhow::{anyhow, Context};
26 use lemmy_db_queries::{source::activity::Activity_, ApubObject, DbPool};
27 use lemmy_db_schema::source::{
32 private_message::PrivateMessage,
35 use lemmy_structs::blocking;
36 use lemmy_utils::{location_info, settings::Settings, LemmyError};
37 use lemmy_websocket::LemmyContext;
40 use url::{ParseError, Url};
42 /// Activitystreams type for community
43 type GroupExt = Ext2<ApActor<ApObject<Group>>, GroupExtension, PublicKeyExtension>;
44 /// Activitystreams type for user
45 type PersonExt = Ext1<ApActor<ApObject<Person>>, PublicKeyExtension>;
46 /// Activitystreams type for post
47 type PageExt = Ext1<ApObject<Page>, PageExtension>;
48 type NoteExt = ApObject<Note>;
50 pub static APUB_JSON_CONTENT_TYPE: &str = "application/activity+json";
52 /// Checks if the ID is allowed for sending or receiving.
54 /// In particular, it checks for:
55 /// - federation being enabled (if its disabled, only local URLs are allowed)
56 /// - the correct scheme (either http or https)
57 /// - URL being in the allowlist (if it is active)
58 /// - URL not being in the blocklist (if it is active)
60 /// Note that only one of allowlist and blacklist can be enabled, not both.
61 fn check_is_apub_id_valid(apub_id: &Url) -> Result<(), LemmyError> {
62 let settings = Settings::get();
63 let domain = apub_id.domain().context(location_info!())?.to_string();
64 let local_instance = settings.get_hostname_without_port()?;
66 if !settings.federation.enabled {
67 return if domain == local_instance {
72 "Trying to connect with {}, but federation is disabled",
80 let host = apub_id.host_str().context(location_info!())?;
81 let host_as_ip = host.parse::<IpAddr>();
82 if host == "localhost" || host_as_ip.is_ok() {
83 return Err(anyhow!("invalid hostname: {:?}", host).into());
86 if apub_id.scheme() != Settings::get().get_protocol_string() {
87 return Err(anyhow!("invalid apub id scheme: {:?}", apub_id.scheme()).into());
90 let mut allowed_instances = Settings::get().get_allowed_instances();
91 let blocked_instances = Settings::get().get_blocked_instances();
92 if allowed_instances.is_empty() && blocked_instances.is_empty() {
94 } else if !allowed_instances.is_empty() {
95 // need to allow this explicitly because apub receive might contain objects from our local
96 // instance. split is needed to remove the port in our federation test setup.
97 allowed_instances.push(local_instance);
99 if allowed_instances.contains(&domain) {
102 Err(anyhow!("{} not in federation allowlist", domain).into())
104 } else if !blocked_instances.is_empty() {
105 if blocked_instances.contains(&domain) {
106 Err(anyhow!("{} is in federation blocklist", domain).into())
111 panic!("Invalid config, both allowed_instances and blocked_instances are specified");
115 /// Common functions for ActivityPub objects, which are implemented by most (but not all) objects
116 /// and actors in Lemmy.
117 #[async_trait::async_trait(?Send)]
118 pub trait ApubObjectType {
119 async fn send_create(&self, creator: &User_, context: &LemmyContext) -> Result<(), LemmyError>;
120 async fn send_update(&self, creator: &User_, context: &LemmyContext) -> Result<(), LemmyError>;
121 async fn send_delete(&self, creator: &User_, context: &LemmyContext) -> Result<(), LemmyError>;
122 async fn send_undo_delete(
125 context: &LemmyContext,
126 ) -> Result<(), LemmyError>;
127 async fn send_remove(&self, mod_: &User_, context: &LemmyContext) -> Result<(), LemmyError>;
128 async fn send_undo_remove(&self, mod_: &User_, context: &LemmyContext) -> Result<(), LemmyError>;
131 #[async_trait::async_trait(?Send)]
132 pub trait ApubLikeableType {
133 async fn send_like(&self, creator: &User_, context: &LemmyContext) -> Result<(), LemmyError>;
134 async fn send_dislike(&self, creator: &User_, context: &LemmyContext) -> Result<(), LemmyError>;
135 async fn send_undo_like(&self, creator: &User_, context: &LemmyContext)
136 -> Result<(), LemmyError>;
139 /// Common methods provided by ActivityPub actors (community and user). Not all methods are
140 /// implemented by all actors.
141 #[async_trait::async_trait(?Send)]
142 pub trait ActorType {
143 fn actor_id_str(&self) -> String;
145 // TODO: every actor should have a public key, so this shouldnt be an option (needs to be fixed in db)
146 fn public_key(&self) -> Option<String>;
147 fn private_key(&self) -> Option<String>;
149 async fn send_follow(
151 follow_actor_id: &Url,
152 context: &LemmyContext,
153 ) -> Result<(), LemmyError>;
154 async fn send_unfollow(
156 follow_actor_id: &Url,
157 context: &LemmyContext,
158 ) -> Result<(), LemmyError>;
160 async fn send_accept_follow(
163 context: &LemmyContext,
164 ) -> Result<(), LemmyError>;
166 async fn send_delete(&self, context: &LemmyContext) -> Result<(), LemmyError>;
167 async fn send_undo_delete(&self, context: &LemmyContext) -> Result<(), LemmyError>;
169 async fn send_remove(&self, context: &LemmyContext) -> Result<(), LemmyError>;
170 async fn send_undo_remove(&self, context: &LemmyContext) -> Result<(), LemmyError>;
172 async fn send_announce(
175 context: &LemmyContext,
176 ) -> Result<(), LemmyError>;
178 /// For a given community, returns the inboxes of all followers.
179 async fn get_follower_inboxes(&self, pool: &DbPool) -> Result<Vec<Url>, LemmyError>;
181 fn actor_id(&self) -> Result<Url, ParseError> {
182 Url::parse(&self.actor_id_str())
185 // TODO move these to the db rows
186 fn get_inbox_url(&self) -> Result<Url, ParseError> {
187 Url::parse(&format!("{}/inbox", &self.actor_id_str()))
190 fn get_shared_inbox_url(&self) -> Result<Url, LemmyError> {
191 let actor_id = self.actor_id()?;
195 &actor_id.host_str().context(location_info!())?,
196 if let Some(port) = actor_id.port() {
202 Ok(Url::parse(&url)?)
205 fn get_outbox_url(&self) -> Result<Url, ParseError> {
206 Url::parse(&format!("{}/outbox", &self.actor_id_str()))
209 fn get_followers_url(&self) -> Result<Url, ParseError> {
210 Url::parse(&format!("{}/followers", &self.actor_id_str()))
213 fn get_public_key_ext(&self) -> Result<PublicKeyExtension, LemmyError> {
216 id: format!("{}#main-key", self.actor_id_str()),
217 owner: self.actor_id_str(),
218 public_key_pem: self.public_key().context(location_info!())?,
225 /// Store a sent or received activity in the database, for logging purposes. These records are not
227 pub(crate) async fn insert_activity<T>(
233 ) -> Result<(), LemmyError>
235 T: Serialize + std::fmt::Debug + Send + 'static,
237 let ap_id = ap_id.to_string();
238 blocking(pool, move |conn| {
239 Activity::insert(conn, ap_id, &activity, local, sensitive)
245 pub(crate) enum PostOrComment {
250 /// Tries to find a post or comment in the local database, without any network requests.
251 /// This is used to handle deletions and removals, because in case we dont have the object, we can
252 /// simply ignore the activity.
253 pub(crate) async fn find_post_or_comment_by_id(
254 context: &LemmyContext,
256 ) -> Result<PostOrComment, LemmyError> {
257 let ap_id = apub_id.to_string();
258 let post = blocking(context.pool(), move |conn| {
259 Post::read_from_apub_id(conn, &ap_id)
262 if let Ok(p) = post {
263 return Ok(PostOrComment::Post(p));
266 let ap_id = apub_id.to_string();
267 let comment = blocking(context.pool(), move |conn| {
268 Comment::read_from_apub_id(conn, &ap_id)
271 if let Ok(c) = comment {
272 return Ok(PostOrComment::Comment(c));
278 pub(crate) enum Object {
281 Community(Community),
283 PrivateMessage(PrivateMessage),
286 pub(crate) async fn find_object_by_id(
287 context: &LemmyContext,
289 ) -> Result<Object, LemmyError> {
290 if let Ok(pc) = find_post_or_comment_by_id(context, apub_id.to_owned()).await {
292 PostOrComment::Post(p) => Object::Post(p),
293 PostOrComment::Comment(c) => Object::Comment(c),
297 let ap_id = apub_id.to_string();
298 let user = blocking(context.pool(), move |conn| {
299 User_::read_from_apub_id(conn, &ap_id)
302 if let Ok(u) = user {
303 return Ok(Object::User(u));
306 let ap_id = apub_id.to_string();
307 let community = blocking(context.pool(), move |conn| {
308 Community::read_from_apub_id(conn, &ap_id)
311 if let Ok(c) = community {
312 return Ok(Object::Community(c));
315 let ap_id = apub_id.to_string();
316 let private_message = blocking(context.pool(), move |conn| {
317 PrivateMessage::read_from_apub_id(conn, &ap_id)
320 if let Ok(pm) = private_message {
321 return Ok(Object::PrivateMessage(pm));