]> Untitled Git - lemmy.git/blob - crates/apub/src/lib.rs
64cfa0f831def669b2b8764bc913fa83ca17d301
[lemmy.git] / crates / apub / src / lib.rs
1 use crate::fetcher::post_or_comment::PostOrComment;
2 use activitypub_federation::{
3   core::signatures::PublicKey,
4   traits::{Actor, ApubObject},
5   InstanceSettingsBuilder,
6   LocalInstance,
7 };
8 use anyhow::Context;
9 use lemmy_api_common::utils::blocking;
10 use lemmy_db_schema::{newtypes::DbUrl, source::activity::Activity, utils::DbPool};
11 use lemmy_utils::{
12   error::LemmyError,
13   location_info,
14   settings::{structs::Settings, SETTINGS},
15 };
16 use lemmy_websocket::LemmyContext;
17 use once_cell::sync::{Lazy, OnceCell};
18 use url::{ParseError, Url};
19
20 pub mod activities;
21 pub(crate) mod activity_lists;
22 pub(crate) mod collections;
23 pub mod fetcher;
24 pub mod http;
25 pub(crate) mod mentions;
26 pub mod objects;
27 pub mod protocol;
28
29 static CONTEXT: Lazy<Vec<serde_json::Value>> = Lazy::new(|| {
30   serde_json::from_str(include_str!("../assets/lemmy/context.json")).expect("parse context")
31 });
32
33 // TODO: store this in context? but its only used in this crate, no need to expose it elsewhere
34 fn local_instance(context: &LemmyContext) -> &'static LocalInstance {
35   static LOCAL_INSTANCE: OnceCell<LocalInstance> = OnceCell::new();
36   LOCAL_INSTANCE.get_or_init(|| {
37     let settings = InstanceSettingsBuilder::default()
38       .http_fetch_retry_limit(context.settings().federation.http_fetch_retry_limit)
39       .worker_count(context.settings().federation.worker_count)
40       .debug(context.settings().federation.debug)
41       // TODO No idea why, but you can't pass context.settings() to the verify_url_function closure
42       // without the value getting captured.
43       .verify_url_function(|url| check_apub_id_valid(url, &SETTINGS.to_owned()))
44       .build()
45       .expect("configure federation");
46     LocalInstance::new(
47       context.settings().hostname.to_owned(),
48       context.client().clone(),
49       settings,
50     )
51   })
52 }
53
54 /// Checks if the ID is allowed for sending or receiving.
55 ///
56 /// In particular, it checks for:
57 /// - federation being enabled (if its disabled, only local URLs are allowed)
58 /// - the correct scheme (either http or https)
59 /// - URL being in the allowlist (if it is active)
60 /// - URL not being in the blocklist (if it is active)
61 ///
62 /// `use_strict_allowlist` should be true only when parsing a remote community, or when parsing a
63 /// post/comment in a local community.
64 #[tracing::instrument(skip(settings))]
65 fn check_apub_id_valid(apub_id: &Url, settings: &Settings) -> Result<(), &'static str> {
66   let domain = apub_id.domain().expect("apud id has domain").to_string();
67   let local_instance = settings
68     .get_hostname_without_port()
69     .expect("local hostname is valid");
70   if domain == local_instance {
71     return Ok(());
72   }
73
74   if !settings.federation.enabled {
75     return Err("Federation disabled");
76   }
77
78   if apub_id.scheme() != settings.get_protocol_string() {
79     return Err("Invalid protocol scheme");
80   }
81
82   if let Some(blocked) = settings.to_owned().federation.blocked_instances {
83     if blocked.contains(&domain) {
84       return Err("Domain is blocked");
85     }
86   }
87
88   if let Some(allowed) = settings.to_owned().federation.allowed_instances {
89     if !allowed.contains(&domain) {
90       return Err("Domain is not in allowlist");
91     }
92   }
93
94   Ok(())
95 }
96
97 #[tracing::instrument(skip(settings))]
98 pub(crate) fn check_apub_id_valid_with_strictness(
99   apub_id: &Url,
100   is_strict: bool,
101   settings: &Settings,
102 ) -> Result<(), LemmyError> {
103   check_apub_id_valid(apub_id, settings).map_err(LemmyError::from_message)?;
104   let domain = apub_id.domain().expect("apud id has domain").to_string();
105   let local_instance = settings
106     .get_hostname_without_port()
107     .expect("local hostname is valid");
108   if domain == local_instance {
109     return Ok(());
110   }
111
112   if let Some(mut allowed) = settings.to_owned().federation.allowed_instances {
113     // Only check allowlist if this is a community, or strict allowlist is enabled.
114     let strict_allowlist = settings.to_owned().federation.strict_allowlist;
115     if is_strict || strict_allowlist {
116       // need to allow this explicitly because apub receive might contain objects from our local
117       // instance.
118       allowed.push(local_instance);
119
120       if !allowed.contains(&domain) {
121         return Err(LemmyError::from_message(
122           "Federation forbidden by strict allowlist",
123         ));
124       }
125     }
126   }
127   Ok(())
128 }
129
130 pub enum EndpointType {
131   Community,
132   Person,
133   Post,
134   Comment,
135   PrivateMessage,
136 }
137
138 /// Generates an apub endpoint for a given domain, IE xyz.tld
139 pub fn generate_local_apub_endpoint(
140   endpoint_type: EndpointType,
141   name: &str,
142   domain: &str,
143 ) -> Result<DbUrl, ParseError> {
144   let point = match endpoint_type {
145     EndpointType::Community => "c",
146     EndpointType::Person => "u",
147     EndpointType::Post => "post",
148     EndpointType::Comment => "comment",
149     EndpointType::PrivateMessage => "private_message",
150   };
151
152   Ok(Url::parse(&format!("{}/{}/{}", domain, point, name))?.into())
153 }
154
155 pub fn generate_followers_url(actor_id: &DbUrl) -> Result<DbUrl, ParseError> {
156   Ok(Url::parse(&format!("{}/followers", actor_id))?.into())
157 }
158
159 pub fn generate_inbox_url(actor_id: &DbUrl) -> Result<DbUrl, ParseError> {
160   Ok(Url::parse(&format!("{}/inbox", actor_id))?.into())
161 }
162
163 pub fn generate_site_inbox_url(actor_id: &DbUrl) -> Result<DbUrl, ParseError> {
164   let mut actor_id: Url = actor_id.clone().into();
165   actor_id.set_path("site_inbox");
166   Ok(actor_id.into())
167 }
168
169 pub fn generate_shared_inbox_url(actor_id: &DbUrl) -> Result<DbUrl, LemmyError> {
170   let actor_id: Url = actor_id.clone().into();
171   let url = format!(
172     "{}://{}{}/inbox",
173     &actor_id.scheme(),
174     &actor_id.host_str().context(location_info!())?,
175     if let Some(port) = actor_id.port() {
176       format!(":{}", port)
177     } else {
178       "".to_string()
179     },
180   );
181   Ok(Url::parse(&url)?.into())
182 }
183
184 pub fn generate_outbox_url(actor_id: &DbUrl) -> Result<DbUrl, ParseError> {
185   Ok(Url::parse(&format!("{}/outbox", actor_id))?.into())
186 }
187
188 fn generate_moderators_url(community_id: &DbUrl) -> Result<DbUrl, LemmyError> {
189   Ok(Url::parse(&format!("{}/moderators", community_id))?.into())
190 }
191
192 /// Store a sent or received activity in the database, for logging purposes. These records are not
193 /// persistent.
194 #[tracing::instrument(skip(pool))]
195 async fn insert_activity(
196   ap_id: &Url,
197   activity: serde_json::Value,
198   local: bool,
199   sensitive: bool,
200   pool: &DbPool,
201 ) -> Result<bool, LemmyError> {
202   let ap_id = ap_id.to_owned().into();
203   Ok(
204     blocking(pool, move |conn| {
205       Activity::insert(conn, ap_id, activity, local, sensitive)
206     })
207     .await??,
208   )
209 }
210
211 /// Common methods provided by ActivityPub actors (community and person). Not all methods are
212 /// implemented by all actors.
213 pub trait ActorType: Actor + ApubObject {
214   fn actor_id(&self) -> Url;
215
216   fn private_key(&self) -> Option<String>;
217
218   fn get_public_key(&self) -> PublicKey {
219     PublicKey::new_main_key(self.actor_id(), self.public_key().to_string())
220   }
221 }