1 use crate::fetcher::post_or_comment::PostOrComment;
2 use activitypub_federation::{
3 core::signatures::PublicKey,
4 traits::{Actor, ApubObject},
9 use async_trait::async_trait;
10 use lemmy_api_common::context::LemmyContext;
11 use lemmy_db_schema::{
12 source::{activity::Activity, instance::Instance, local_site::LocalSite},
15 use lemmy_utils::{error::LemmyError, settings::structs::Settings};
16 use once_cell::sync::Lazy;
17 use tokio::sync::OnceCell;
21 pub(crate) mod activity_lists;
23 pub(crate) mod collections;
26 pub(crate) mod mentions;
30 const FEDERATION_HTTP_FETCH_LIMIT: i32 = 25;
32 static CONTEXT: Lazy<Vec<serde_json::Value>> = Lazy::new(|| {
33 serde_json::from_str(include_str!("../assets/lemmy/context.json")).expect("parse context")
36 // TODO: store this in context? but its only used in this crate, no need to expose it elsewhere
37 // TODO this singleton needs to be redone to account for live data.
38 async fn local_instance(context: &LemmyContext) -> &'static LocalInstance {
39 static LOCAL_INSTANCE: OnceCell<LocalInstance> = OnceCell::const_new();
41 .get_or_init(|| async {
42 // Local site may be missing
43 let local_site = &LocalSite::read(context.pool()).await;
44 let worker_count = local_site
46 .map(|l| l.federation_worker_count)
47 .unwrap_or(64) as u64;
49 let settings = InstanceSettings::builder()
50 .http_fetch_retry_limit(FEDERATION_HTTP_FETCH_LIMIT)
51 .worker_count(worker_count)
52 .debug(cfg!(debug_assertions))
53 .http_signature_compat(true)
54 .url_verifier(Box::new(VerifyUrlData(context.clone())))
56 .expect("configure federation");
58 context.settings().hostname.clone(),
59 context.client().clone(),
67 struct VerifyUrlData(LemmyContext);
70 impl UrlVerifier for VerifyUrlData {
71 async fn verify(&self, url: &Url) -> Result<(), &'static str> {
72 let local_site_data = fetch_local_site_data(self.0.pool())
74 .expect("read local site data");
75 check_apub_id_valid(url, &local_site_data, self.0.settings())
79 /// Checks if the ID is allowed for sending or receiving.
81 /// In particular, it checks for:
82 /// - federation being enabled (if its disabled, only local URLs are allowed)
83 /// - the correct scheme (either http or https)
84 /// - URL being in the allowlist (if it is active)
85 /// - URL not being in the blocklist (if it is active)
87 /// `use_strict_allowlist` should be true only when parsing a remote community, or when parsing a
88 /// post/comment in a local community.
89 #[tracing::instrument(skip(settings, local_site_data))]
90 fn check_apub_id_valid(
92 local_site_data: &LocalSiteData,
94 ) -> Result<(), &'static str> {
95 let domain = apub_id.domain().expect("apud id has domain").to_string();
96 let local_instance = settings
97 .get_hostname_without_port()
98 .expect("local hostname is valid");
99 if domain == local_instance {
106 .map(|l| l.federation_enabled)
109 return Err("Federation disabled");
112 if apub_id.scheme() != settings.get_protocol_string() {
113 return Err("Invalid protocol scheme");
116 if let Some(blocked) = local_site_data.blocked_instances.as_ref() {
117 if blocked.iter().any(|i| domain.eq(&i.domain)) {
118 return Err("Domain is blocked");
122 if let Some(allowed) = local_site_data.allowed_instances.as_ref() {
123 if !allowed.iter().any(|i| domain.eq(&i.domain)) {
124 return Err("Domain is not in allowlist");
132 pub(crate) struct LocalSiteData {
133 local_site: Option<LocalSite>,
134 allowed_instances: Option<Vec<Instance>>,
135 blocked_instances: Option<Vec<Instance>>,
138 pub(crate) async fn fetch_local_site_data(
140 ) -> Result<LocalSiteData, diesel::result::Error> {
141 // LocalSite may be missing
142 let local_site = LocalSite::read(pool).await.ok();
143 let allowed = Instance::allowlist(pool).await?;
144 let blocked = Instance::blocklist(pool).await?;
146 // These can return empty vectors, so convert them to options
147 let allowed_instances = (!allowed.is_empty()).then_some(allowed);
148 let blocked_instances = (!blocked.is_empty()).then_some(blocked);
157 #[tracing::instrument(skip(settings, local_site_data))]
158 pub(crate) fn check_apub_id_valid_with_strictness(
161 local_site_data: &LocalSiteData,
163 ) -> Result<(), LemmyError> {
164 check_apub_id_valid(apub_id, local_site_data, settings).map_err(LemmyError::from_message)?;
165 let domain = apub_id.domain().expect("apud id has domain").to_string();
166 let local_instance = settings
167 .get_hostname_without_port()
168 .expect("local hostname is valid");
169 if domain == local_instance {
173 if let Some(allowed) = local_site_data.allowed_instances.as_ref() {
174 // Only check allowlist if this is a community
176 // need to allow this explicitly because apub receive might contain objects from our local
178 let mut allowed_and_local = allowed
180 .map(|i| i.domain.clone())
181 .collect::<Vec<String>>();
182 allowed_and_local.push(local_instance);
184 if !allowed_and_local.contains(&domain) {
185 return Err(LemmyError::from_message(
186 "Federation forbidden by strict allowlist",
194 /// Store a sent or received activity in the database, for logging purposes. These records are not
196 #[tracing::instrument(skip(pool))]
197 async fn insert_activity(
199 activity: serde_json::Value,
203 ) -> Result<bool, LemmyError> {
204 let ap_id = ap_id.clone().into();
205 Ok(Activity::insert(pool, ap_id, activity, local, Some(sensitive)).await?)
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;
213 fn private_key(&self) -> Option<String>;
215 fn get_public_key(&self) -> PublicKey {
216 PublicKey::new_main_key(self.actor_id(), self.public_key().to_string())
220 #[async_trait::async_trait(?Send)]
221 pub trait SendActivity {
224 async fn send_activity(
226 _response: &Self::Response,
227 _context: &LemmyContext,
228 ) -> Result<(), LemmyError> {