]> Untitled Git - lemmy.git/blob - crates/apub/src/lib.rs
Moving settings to Database. (#2492)
[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   InstanceSettings,
6   LocalInstance,
7 };
8 use anyhow::Context;
9 use diesel::PgConnection;
10 use lemmy_api_common::utils::blocking;
11 use lemmy_db_schema::{
12   newtypes::DbUrl,
13   source::{activity::Activity, instance::Instance, local_site::LocalSite},
14   utils::DbPool,
15 };
16 use lemmy_utils::{error::LemmyError, location_info, settings::structs::Settings};
17 use lemmy_websocket::LemmyContext;
18 use once_cell::sync::{Lazy, OnceCell};
19 use url::{ParseError, Url};
20
21 pub mod activities;
22 pub(crate) mod activity_lists;
23 pub(crate) mod collections;
24 pub mod fetcher;
25 pub mod http;
26 pub(crate) mod mentions;
27 pub mod objects;
28 pub mod protocol;
29
30 static CONTEXT: Lazy<Vec<serde_json::Value>> = Lazy::new(|| {
31   serde_json::from_str(include_str!("../assets/lemmy/context.json")).expect("parse context")
32 });
33
34 // TODO: store this in context? but its only used in this crate, no need to expose it elsewhere
35 // TODO this singleton needs to be redone to account for live data.
36 fn local_instance(context: &LemmyContext) -> &'static LocalInstance {
37   static LOCAL_INSTANCE: OnceCell<LocalInstance> = OnceCell::new();
38   LOCAL_INSTANCE.get_or_init(|| {
39     let conn = &mut context
40       .pool()
41       .get()
42       .expect("getting connection for LOCAL_INSTANCE init");
43     // Local site may be missing
44     let local_site = &LocalSite::read(conn);
45     let worker_count = local_site
46       .as_ref()
47       .map(|l| l.federation_worker_count)
48       .unwrap_or(64) as u64;
49     let http_fetch_retry_limit = local_site
50       .as_ref()
51       .map(|l| l.federation_http_fetch_retry_limit)
52       .unwrap_or(25);
53     let federation_debug = local_site
54       .as_ref()
55       .map(|l| l.federation_debug)
56       .unwrap_or(true);
57
58     let settings = InstanceSettings::builder()
59       .http_fetch_retry_limit(http_fetch_retry_limit)
60       .worker_count(worker_count)
61       .debug(federation_debug)
62       // TODO No idea why, but you can't pass context.settings() to the verify_url_function closure
63       // without the value getting captured.
64       .http_signature_compat(true)
65       .build()
66       .expect("configure federation");
67     LocalInstance::new(
68       context.settings().hostname.to_owned(),
69       context.client().clone(),
70       settings,
71     )
72   })
73 }
74
75 /// Checks if the ID is allowed for sending or receiving.
76 ///
77 /// In particular, it checks for:
78 /// - federation being enabled (if its disabled, only local URLs are allowed)
79 /// - the correct scheme (either http or https)
80 /// - URL being in the allowlist (if it is active)
81 /// - URL not being in the blocklist (if it is active)
82 ///
83 /// `use_strict_allowlist` should be true only when parsing a remote community, or when parsing a
84 /// post/comment in a local community.
85 #[tracing::instrument(skip(settings, local_site_data))]
86 // TODO This function needs to be called by incoming activities
87 fn check_apub_id_valid(
88   apub_id: &Url,
89   local_site_data: &LocalSiteData,
90   settings: &Settings,
91 ) -> Result<(), &'static str> {
92   let domain = apub_id.domain().expect("apud id has domain").to_string();
93   let local_instance = settings
94     .get_hostname_without_port()
95     .expect("local hostname is valid");
96   if domain == local_instance {
97     return Ok(());
98   }
99
100   if !local_site_data
101     .local_site
102     .as_ref()
103     .map(|l| l.federation_enabled)
104     .unwrap_or(true)
105   {
106     return Err("Federation disabled");
107   }
108
109   if apub_id.scheme() != settings.get_protocol_string() {
110     return Err("Invalid protocol scheme");
111   }
112
113   if let Some(blocked) = local_site_data.blocked_instances.as_ref() {
114     if blocked.contains(&domain) {
115       return Err("Domain is blocked");
116     }
117   }
118
119   if let Some(allowed) = local_site_data.allowed_instances.as_ref() {
120     if !allowed.contains(&domain) {
121       return Err("Domain is not in allowlist");
122     }
123   }
124
125   Ok(())
126 }
127
128 #[derive(Clone)]
129 pub(crate) struct LocalSiteData {
130   local_site: Option<LocalSite>,
131   allowed_instances: Option<Vec<String>>,
132   blocked_instances: Option<Vec<String>>,
133 }
134
135 pub(crate) fn fetch_local_site_data(
136   conn: &mut PgConnection,
137 ) -> Result<LocalSiteData, diesel::result::Error> {
138   // LocalSite may be missing
139   let local_site = LocalSite::read(conn).ok();
140   let allowed = Instance::allowlist(conn)?;
141   let blocked = Instance::blocklist(conn)?;
142
143   // These can return empty vectors, so convert them to options
144   let allowed_instances = (!allowed.is_empty()).then(|| allowed);
145   let blocked_instances = (!blocked.is_empty()).then(|| blocked);
146
147   Ok(LocalSiteData {
148     local_site,
149     allowed_instances,
150     blocked_instances,
151   })
152 }
153
154 #[tracing::instrument(skip(settings, local_site_data))]
155 pub(crate) fn check_apub_id_valid_with_strictness(
156   apub_id: &Url,
157   is_strict: bool,
158   local_site_data: &LocalSiteData,
159   settings: &Settings,
160 ) -> Result<(), LemmyError> {
161   check_apub_id_valid(apub_id, local_site_data, settings).map_err(LemmyError::from_message)?;
162   let domain = apub_id.domain().expect("apud id has domain").to_string();
163   let local_instance = settings
164     .get_hostname_without_port()
165     .expect("local hostname is valid");
166   if domain == local_instance {
167     return Ok(());
168   }
169
170   if let Some(allowed) = local_site_data.allowed_instances.as_ref() {
171     // Only check allowlist if this is a community, or strict allowlist is enabled.
172     let strict_allowlist = local_site_data
173       .local_site
174       .as_ref()
175       .map(|l| l.federation_strict_allowlist)
176       .unwrap_or(true);
177     if is_strict || strict_allowlist {
178       // need to allow this explicitly because apub receive might contain objects from our local
179       // instance.
180       let mut allowed_and_local = allowed.to_owned();
181       allowed_and_local.push(local_instance);
182
183       if !allowed_and_local.contains(&domain) {
184         return Err(LemmyError::from_message(
185           "Federation forbidden by strict allowlist",
186         ));
187       }
188     }
189   }
190   Ok(())
191 }
192
193 pub enum EndpointType {
194   Community,
195   Person,
196   Post,
197   Comment,
198   PrivateMessage,
199 }
200
201 /// Generates an apub endpoint for a given domain, IE xyz.tld
202 pub fn generate_local_apub_endpoint(
203   endpoint_type: EndpointType,
204   name: &str,
205   domain: &str,
206 ) -> Result<DbUrl, ParseError> {
207   let point = match endpoint_type {
208     EndpointType::Community => "c",
209     EndpointType::Person => "u",
210     EndpointType::Post => "post",
211     EndpointType::Comment => "comment",
212     EndpointType::PrivateMessage => "private_message",
213   };
214
215   Ok(Url::parse(&format!("{}/{}/{}", domain, point, name))?.into())
216 }
217
218 pub fn generate_followers_url(actor_id: &DbUrl) -> Result<DbUrl, ParseError> {
219   Ok(Url::parse(&format!("{}/followers", actor_id))?.into())
220 }
221
222 pub fn generate_inbox_url(actor_id: &DbUrl) -> Result<DbUrl, ParseError> {
223   Ok(Url::parse(&format!("{}/inbox", actor_id))?.into())
224 }
225
226 pub fn generate_site_inbox_url(actor_id: &DbUrl) -> Result<DbUrl, ParseError> {
227   let mut actor_id: Url = actor_id.clone().into();
228   actor_id.set_path("site_inbox");
229   Ok(actor_id.into())
230 }
231
232 pub fn generate_shared_inbox_url(actor_id: &DbUrl) -> Result<DbUrl, LemmyError> {
233   let actor_id: Url = actor_id.clone().into();
234   let url = format!(
235     "{}://{}{}/inbox",
236     &actor_id.scheme(),
237     &actor_id.host_str().context(location_info!())?,
238     if let Some(port) = actor_id.port() {
239       format!(":{}", port)
240     } else {
241       "".to_string()
242     },
243   );
244   Ok(Url::parse(&url)?.into())
245 }
246
247 pub fn generate_outbox_url(actor_id: &DbUrl) -> Result<DbUrl, ParseError> {
248   Ok(Url::parse(&format!("{}/outbox", actor_id))?.into())
249 }
250
251 fn generate_moderators_url(community_id: &DbUrl) -> Result<DbUrl, LemmyError> {
252   Ok(Url::parse(&format!("{}/moderators", community_id))?.into())
253 }
254
255 /// Store a sent or received activity in the database, for logging purposes. These records are not
256 /// persistent.
257 #[tracing::instrument(skip(pool))]
258 async fn insert_activity(
259   ap_id: &Url,
260   activity: serde_json::Value,
261   local: bool,
262   sensitive: bool,
263   pool: &DbPool,
264 ) -> Result<bool, LemmyError> {
265   let ap_id = ap_id.to_owned().into();
266   Ok(
267     blocking(pool, move |conn| {
268       Activity::insert(conn, ap_id, activity, local, Some(sensitive))
269     })
270     .await??,
271   )
272 }
273
274 /// Common methods provided by ActivityPub actors (community and person). Not all methods are
275 /// implemented by all actors.
276 pub trait ActorType: Actor + ApubObject {
277   fn actor_id(&self) -> Url;
278
279   fn private_key(&self) -> Option<String>;
280
281   fn get_public_key(&self) -> PublicKey {
282     PublicKey::new_main_key(self.actor_id(), self.public_key().to_string())
283   }
284 }