]> Untitled Git - lemmy.git/blob - crates/apub/src/lib.rs
Move code to generate apub urls into lemmy_api_common
[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   UrlVerifier,
8 };
9 use async_trait::async_trait;
10 use lemmy_api_common::LemmyContext;
11 use lemmy_db_schema::{
12   source::{activity::Activity, instance::Instance, local_site::LocalSite},
13   utils::DbPool,
14 };
15 use lemmy_utils::{error::LemmyError, settings::structs::Settings};
16 use once_cell::sync::Lazy;
17 use tokio::sync::OnceCell;
18 use url::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 const FEDERATION_HTTP_FETCH_LIMIT: i32 = 25;
30
31 static CONTEXT: Lazy<Vec<serde_json::Value>> = Lazy::new(|| {
32   serde_json::from_str(include_str!("../assets/lemmy/context.json")).expect("parse context")
33 });
34
35 // TODO: store this in context? but its only used in this crate, no need to expose it elsewhere
36 // TODO this singleton needs to be redone to account for live data.
37 async fn local_instance(context: &LemmyContext) -> &'static LocalInstance {
38   static LOCAL_INSTANCE: OnceCell<LocalInstance> = OnceCell::const_new();
39   LOCAL_INSTANCE
40     .get_or_init(|| async {
41       // Local site may be missing
42       let local_site = &LocalSite::read(context.pool()).await;
43       let worker_count = local_site
44         .as_ref()
45         .map(|l| l.federation_worker_count)
46         .unwrap_or(64) as u64;
47       let federation_debug = local_site
48         .as_ref()
49         .map(|l| l.federation_debug)
50         .unwrap_or(true);
51
52       let settings = InstanceSettings::builder()
53         .http_fetch_retry_limit(FEDERATION_HTTP_FETCH_LIMIT)
54         .worker_count(worker_count)
55         .debug(federation_debug)
56         .http_signature_compat(true)
57         .url_verifier(Box::new(VerifyUrlData(context.clone())))
58         .build()
59         .expect("configure federation");
60       LocalInstance::new(
61         context.settings().hostname.clone(),
62         context.client().clone(),
63         settings,
64       )
65     })
66     .await
67 }
68
69 #[derive(Clone)]
70 struct VerifyUrlData(LemmyContext);
71
72 #[async_trait]
73 impl UrlVerifier for VerifyUrlData {
74   async fn verify(&self, url: &Url) -> Result<(), &'static str> {
75     let local_site_data = fetch_local_site_data(self.0.pool())
76       .await
77       .expect("read local site data");
78     check_apub_id_valid(url, &local_site_data, self.0.settings())
79   }
80 }
81
82 /// Checks if the ID is allowed for sending or receiving.
83 ///
84 /// In particular, it checks for:
85 /// - federation being enabled (if its disabled, only local URLs are allowed)
86 /// - the correct scheme (either http or https)
87 /// - URL being in the allowlist (if it is active)
88 /// - URL not being in the blocklist (if it is active)
89 ///
90 /// `use_strict_allowlist` should be true only when parsing a remote community, or when parsing a
91 /// post/comment in a local community.
92 #[tracing::instrument(skip(settings, local_site_data))]
93 fn check_apub_id_valid(
94   apub_id: &Url,
95   local_site_data: &LocalSiteData,
96   settings: &Settings,
97 ) -> Result<(), &'static str> {
98   let domain = apub_id.domain().expect("apud id has domain").to_string();
99   let local_instance = settings
100     .get_hostname_without_port()
101     .expect("local hostname is valid");
102   if domain == local_instance {
103     return Ok(());
104   }
105
106   if !local_site_data
107     .local_site
108     .as_ref()
109     .map(|l| l.federation_enabled)
110     .unwrap_or(true)
111   {
112     return Err("Federation disabled");
113   }
114
115   if apub_id.scheme() != settings.get_protocol_string() {
116     return Err("Invalid protocol scheme");
117   }
118
119   if let Some(blocked) = local_site_data.blocked_instances.as_ref() {
120     if blocked.contains(&domain) {
121       return Err("Domain is blocked");
122     }
123   }
124
125   if let Some(allowed) = local_site_data.allowed_instances.as_ref() {
126     if !allowed.contains(&domain) {
127       return Err("Domain is not in allowlist");
128     }
129   }
130
131   Ok(())
132 }
133
134 #[derive(Clone)]
135 pub(crate) struct LocalSiteData {
136   local_site: Option<LocalSite>,
137   allowed_instances: Option<Vec<String>>,
138   blocked_instances: Option<Vec<String>>,
139 }
140
141 pub(crate) async fn fetch_local_site_data(
142   pool: &DbPool,
143 ) -> Result<LocalSiteData, diesel::result::Error> {
144   // LocalSite may be missing
145   let local_site = LocalSite::read(pool).await.ok();
146   let allowed = Instance::allowlist(pool).await?;
147   let blocked = Instance::blocklist(pool).await?;
148
149   // These can return empty vectors, so convert them to options
150   let allowed_instances = (!allowed.is_empty()).then_some(allowed);
151   let blocked_instances = (!blocked.is_empty()).then_some(blocked);
152
153   Ok(LocalSiteData {
154     local_site,
155     allowed_instances,
156     blocked_instances,
157   })
158 }
159
160 #[tracing::instrument(skip(settings, local_site_data))]
161 pub(crate) fn check_apub_id_valid_with_strictness(
162   apub_id: &Url,
163   is_strict: bool,
164   local_site_data: &LocalSiteData,
165   settings: &Settings,
166 ) -> Result<(), LemmyError> {
167   check_apub_id_valid(apub_id, local_site_data, settings).map_err(LemmyError::from_message)?;
168   let domain = apub_id.domain().expect("apud id has domain").to_string();
169   let local_instance = settings
170     .get_hostname_without_port()
171     .expect("local hostname is valid");
172   if domain == local_instance {
173     return Ok(());
174   }
175
176   if let Some(allowed) = local_site_data.allowed_instances.as_ref() {
177     // Only check allowlist if this is a community
178     if is_strict {
179       // need to allow this explicitly because apub receive might contain objects from our local
180       // instance.
181       let mut allowed_and_local = allowed.clone();
182       allowed_and_local.push(local_instance);
183
184       if !allowed_and_local.contains(&domain) {
185         return Err(LemmyError::from_message(
186           "Federation forbidden by strict allowlist",
187         ));
188       }
189     }
190   }
191   Ok(())
192 }
193
194 /// Store a sent or received activity in the database, for logging purposes. These records are not
195 /// persistent.
196 #[tracing::instrument(skip(pool))]
197 async fn insert_activity(
198   ap_id: &Url,
199   activity: serde_json::Value,
200   local: bool,
201   sensitive: bool,
202   pool: &DbPool,
203 ) -> Result<bool, LemmyError> {
204   let ap_id = ap_id.clone().into();
205   Ok(Activity::insert(pool, ap_id, activity, local, Some(sensitive)).await?)
206 }
207
208 /// Common methods provided by ActivityPub actors (community and person). Not all methods are
209 /// implemented by all actors.
210 pub trait ActorType: Actor + ApubObject {
211   fn actor_id(&self) -> Url;
212
213   fn private_key(&self) -> Option<String>;
214
215   fn get_public_key(&self) -> PublicKey {
216     PublicKey::new_main_key(self.actor_id(), self.public_key().to_string())
217   }
218 }