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::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;
22 pub(crate) mod collections;
25 pub(crate) mod mentions;
29 const FEDERATION_HTTP_FETCH_LIMIT: i32 = 25;
31 static CONTEXT: Lazy<Vec<serde_json::Value>> = Lazy::new(|| {
32 serde_json::from_str(include_str!("../assets/lemmy/context.json")).expect("parse context")
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();
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
45 .map(|l| l.federation_worker_count)
46 .unwrap_or(64) as u64;
47 let federation_debug = local_site
49 .map(|l| l.federation_debug)
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())))
59 .expect("configure federation");
61 context.settings().hostname.clone(),
62 context.client().clone(),
70 struct VerifyUrlData(LemmyContext);
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())
77 .expect("read local site data");
78 check_apub_id_valid(url, &local_site_data, self.0.settings())
82 /// Checks if the ID is allowed for sending or receiving.
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)
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(
95 local_site_data: &LocalSiteData,
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 {
109 .map(|l| l.federation_enabled)
112 return Err("Federation disabled");
115 if apub_id.scheme() != settings.get_protocol_string() {
116 return Err("Invalid protocol scheme");
119 if let Some(blocked) = local_site_data.blocked_instances.as_ref() {
120 if blocked.contains(&domain) {
121 return Err("Domain is blocked");
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");
135 pub(crate) struct LocalSiteData {
136 local_site: Option<LocalSite>,
137 allowed_instances: Option<Vec<String>>,
138 blocked_instances: Option<Vec<String>>,
141 pub(crate) async fn fetch_local_site_data(
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?;
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);
160 #[tracing::instrument(skip(settings, local_site_data))]
161 pub(crate) fn check_apub_id_valid_with_strictness(
164 local_site_data: &LocalSiteData,
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 {
176 if let Some(allowed) = local_site_data.allowed_instances.as_ref() {
177 // Only check allowlist if this is a community
179 // need to allow this explicitly because apub receive might contain objects from our local
181 let mut allowed_and_local = allowed.clone();
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())