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::{Page, Tombstone},
23 use activitystreams_ext::{Ext1, Ext2};
24 use anyhow::{anyhow, Context};
25 use lemmy_db::{activity::Activity, user::User_, DbPool};
26 use lemmy_structs::blocking;
27 use lemmy_utils::{location_info, settings::Settings, LemmyError};
28 use lemmy_websocket::LemmyContext;
31 use url::{ParseError, Url};
33 /// Activitystreams type for community
34 type GroupExt = Ext2<ApActor<Group>, GroupExtension, PublicKeyExtension>;
35 /// Activitystreams type for user
36 type PersonExt = Ext1<ApActor<Person>, PublicKeyExtension>;
37 /// Activitystreams type for post
38 type PageExt = Ext1<Page, PageExtension>;
40 pub static APUB_JSON_CONTENT_TYPE: &str = "application/activity+json";
42 /// Checks if the ID is allowed for sending or receiving.
44 /// In particular, it checks for:
45 /// - federation being enabled (if its disabled, only local URLs are allowed)
46 /// - the correct scheme (either http or https)
47 /// - URL being in the allowlist (if it is active)
48 /// - URL not being in the blocklist (if it is active)
50 /// Note that only one of allowlist and blacklist can be enabled, not both.
51 fn check_is_apub_id_valid(apub_id: &Url) -> Result<(), LemmyError> {
52 let settings = Settings::get();
53 let domain = apub_id.domain().context(location_info!())?.to_string();
54 let local_instance = settings
57 .collect::<Vec<&str>>()
59 .context(location_info!())?
62 if !settings.federation.enabled {
63 return if domain == local_instance {
68 "Trying to connect with {}, but federation is disabled",
76 let host = apub_id.host_str().context(location_info!())?;
77 let host_as_ip = host.parse::<IpAddr>();
78 if host == "localhost" || host_as_ip.is_ok() {
79 return Err(anyhow!("invalid hostname: {:?}", host).into());
82 if apub_id.scheme() != Settings::get().get_protocol_string() {
83 return Err(anyhow!("invalid apub id scheme: {:?}", apub_id.scheme()).into());
86 let mut allowed_instances = Settings::get().get_allowed_instances();
87 let blocked_instances = Settings::get().get_blocked_instances();
88 if allowed_instances.is_empty() && blocked_instances.is_empty() {
90 } else if !allowed_instances.is_empty() {
91 // need to allow this explicitly because apub receive might contain objects from our local
92 // instance. split is needed to remove the port in our federation test setup.
93 allowed_instances.push(local_instance);
95 if allowed_instances.contains(&domain) {
98 Err(anyhow!("{} not in federation allowlist", domain).into())
100 } else if !blocked_instances.is_empty() {
101 if blocked_instances.contains(&domain) {
102 Err(anyhow!("{} is in federation blocklist", domain).into())
107 panic!("Invalid config, both allowed_instances and blocked_instances are specified");
111 /// Trait for converting an object or actor into the respective ActivityPub type.
112 #[async_trait::async_trait(?Send)]
115 async fn to_apub(&self, pool: &DbPool) -> Result<Self::ApubType, LemmyError>;
116 fn to_tombstone(&self) -> Result<Tombstone, LemmyError>;
119 #[async_trait::async_trait(?Send)]
122 /// Converts an object from ActivityPub type to Lemmy internal type.
124 /// * `apub` The object to read from
125 /// * `context` LemmyContext which holds DB pool, HTTP client etc
126 /// * `expected_domain` If present, ensure that the domains of this and of the apub object ID are
129 apub: &Self::ApubType,
130 context: &LemmyContext,
131 expected_domain: Option<Url>,
132 request_counter: &mut i32,
133 ) -> Result<Self, LemmyError>
138 /// Common functions for ActivityPub objects, which are implemented by most (but not all) objects
139 /// and actors in Lemmy.
140 #[async_trait::async_trait(?Send)]
141 pub trait ApubObjectType {
142 async fn send_create(&self, creator: &User_, context: &LemmyContext) -> Result<(), LemmyError>;
143 async fn send_update(&self, creator: &User_, context: &LemmyContext) -> Result<(), LemmyError>;
144 async fn send_delete(&self, creator: &User_, context: &LemmyContext) -> Result<(), LemmyError>;
145 async fn send_undo_delete(
148 context: &LemmyContext,
149 ) -> Result<(), LemmyError>;
150 async fn send_remove(&self, mod_: &User_, context: &LemmyContext) -> Result<(), LemmyError>;
151 async fn send_undo_remove(&self, mod_: &User_, context: &LemmyContext) -> Result<(), LemmyError>;
154 #[async_trait::async_trait(?Send)]
155 pub trait ApubLikeableType {
156 async fn send_like(&self, creator: &User_, context: &LemmyContext) -> Result<(), LemmyError>;
157 async fn send_dislike(&self, creator: &User_, context: &LemmyContext) -> Result<(), LemmyError>;
158 async fn send_undo_like(&self, creator: &User_, context: &LemmyContext)
159 -> Result<(), LemmyError>;
162 /// Common methods provided by ActivityPub actors (community and user). Not all methods are
163 /// implemented by all actors.
164 #[async_trait::async_trait(?Send)]
165 pub trait ActorType {
166 fn actor_id_str(&self) -> String;
168 // TODO: every actor should have a public key, so this shouldnt be an option (needs to be fixed in db)
169 fn public_key(&self) -> Option<String>;
170 fn private_key(&self) -> Option<String>;
172 async fn send_follow(
174 follow_actor_id: &Url,
175 context: &LemmyContext,
176 ) -> Result<(), LemmyError>;
177 async fn send_unfollow(
179 follow_actor_id: &Url,
180 context: &LemmyContext,
181 ) -> Result<(), LemmyError>;
183 async fn send_accept_follow(
186 context: &LemmyContext,
187 ) -> Result<(), LemmyError>;
189 async fn send_delete(&self, context: &LemmyContext) -> Result<(), LemmyError>;
190 async fn send_undo_delete(&self, context: &LemmyContext) -> Result<(), LemmyError>;
192 async fn send_remove(&self, context: &LemmyContext) -> Result<(), LemmyError>;
193 async fn send_undo_remove(&self, context: &LemmyContext) -> Result<(), LemmyError>;
195 async fn send_announce(
198 context: &LemmyContext,
199 ) -> Result<(), LemmyError>;
201 /// For a given community, returns the inboxes of all followers.
202 async fn get_follower_inboxes(&self, pool: &DbPool) -> Result<Vec<Url>, LemmyError>;
204 fn actor_id(&self) -> Result<Url, ParseError> {
205 Url::parse(&self.actor_id_str())
208 // TODO move these to the db rows
209 fn get_inbox_url(&self) -> Result<Url, ParseError> {
210 Url::parse(&format!("{}/inbox", &self.actor_id_str()))
213 fn get_shared_inbox_url(&self) -> Result<Url, LemmyError> {
214 let actor_id = self.actor_id()?;
218 &actor_id.host_str().context(location_info!())?,
219 if let Some(port) = actor_id.port() {
225 Ok(Url::parse(&url)?)
228 fn get_outbox_url(&self) -> Result<Url, ParseError> {
229 Url::parse(&format!("{}/outbox", &self.actor_id_str()))
232 fn get_followers_url(&self) -> Result<Url, ParseError> {
233 Url::parse(&format!("{}/followers", &self.actor_id_str()))
236 fn get_public_key_ext(&self) -> Result<PublicKeyExtension, LemmyError> {
239 id: format!("{}#main-key", self.actor_id_str()),
240 owner: self.actor_id_str(),
241 public_key_pem: self.public_key().context(location_info!())?,
248 /// Store a sent or received activity in the database, for logging purposes. These records are not
250 pub async fn insert_activity<T>(
256 ) -> Result<(), LemmyError>
258 T: Serialize + std::fmt::Debug + Send + 'static,
260 let ap_id = ap_id.to_string();
261 blocking(pool, move |conn| {
262 Activity::insert(conn, ap_id, &activity, local, sensitive)