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;
48 let federation_debug = local_site
50 .map(|l| l.federation_debug)
53 let settings = InstanceSettings::builder()
54 .http_fetch_retry_limit(FEDERATION_HTTP_FETCH_LIMIT)
55 .worker_count(worker_count)
56 .debug(federation_debug)
57 .http_signature_compat(true)
58 .url_verifier(Box::new(VerifyUrlData(context.clone())))
60 .expect("configure federation");
62 context.settings().hostname.clone(),
63 context.client().clone(),
71 struct VerifyUrlData(LemmyContext);
74 impl UrlVerifier for VerifyUrlData {
75 async fn verify(&self, url: &Url) -> Result<(), &'static str> {
76 let local_site_data = fetch_local_site_data(self.0.pool())
78 .expect("read local site data");
79 check_apub_id_valid(url, &local_site_data, self.0.settings())
83 /// Checks if the ID is allowed for sending or receiving.
85 /// In particular, it checks for:
86 /// - federation being enabled (if its disabled, only local URLs are allowed)
87 /// - the correct scheme (either http or https)
88 /// - URL being in the allowlist (if it is active)
89 /// - URL not being in the blocklist (if it is active)
91 /// `use_strict_allowlist` should be true only when parsing a remote community, or when parsing a
92 /// post/comment in a local community.
93 #[tracing::instrument(skip(settings, local_site_data))]
94 fn check_apub_id_valid(
96 local_site_data: &LocalSiteData,
98 ) -> Result<(), &'static str> {
99 let domain = apub_id.domain().expect("apud id has domain").to_string();
100 let local_instance = settings
101 .get_hostname_without_port()
102 .expect("local hostname is valid");
103 if domain == local_instance {
110 .map(|l| l.federation_enabled)
113 return Err("Federation disabled");
116 if apub_id.scheme() != settings.get_protocol_string() {
117 return Err("Invalid protocol scheme");
120 if let Some(blocked) = local_site_data.blocked_instances.as_ref() {
121 if blocked.contains(&domain) {
122 return Err("Domain is blocked");
126 if let Some(allowed) = local_site_data.allowed_instances.as_ref() {
127 if !allowed.contains(&domain) {
128 return Err("Domain is not in allowlist");
136 pub(crate) struct LocalSiteData {
137 local_site: Option<LocalSite>,
138 allowed_instances: Option<Vec<String>>,
139 blocked_instances: Option<Vec<String>>,
142 pub(crate) async fn fetch_local_site_data(
144 ) -> Result<LocalSiteData, diesel::result::Error> {
145 // LocalSite may be missing
146 let local_site = LocalSite::read(pool).await.ok();
147 let allowed = Instance::allowlist(pool).await?;
148 let blocked = Instance::blocklist(pool).await?;
150 // These can return empty vectors, so convert them to options
151 let allowed_instances = (!allowed.is_empty()).then_some(allowed);
152 let blocked_instances = (!blocked.is_empty()).then_some(blocked);
161 #[tracing::instrument(skip(settings, local_site_data))]
162 pub(crate) fn check_apub_id_valid_with_strictness(
165 local_site_data: &LocalSiteData,
167 ) -> Result<(), LemmyError> {
168 check_apub_id_valid(apub_id, local_site_data, settings).map_err(LemmyError::from_message)?;
169 let domain = apub_id.domain().expect("apud id has domain").to_string();
170 let local_instance = settings
171 .get_hostname_without_port()
172 .expect("local hostname is valid");
173 if domain == local_instance {
177 if let Some(allowed) = local_site_data.allowed_instances.as_ref() {
178 // Only check allowlist if this is a community
180 // need to allow this explicitly because apub receive might contain objects from our local
182 let mut allowed_and_local = allowed.clone();
183 allowed_and_local.push(local_instance);
185 if !allowed_and_local.contains(&domain) {
186 return Err(LemmyError::from_message(
187 "Federation forbidden by strict allowlist",
195 /// Store a sent or received activity in the database, for logging purposes. These records are not
197 #[tracing::instrument(skip(pool))]
198 async fn insert_activity(
200 activity: serde_json::Value,
204 ) -> Result<bool, LemmyError> {
205 let ap_id = ap_id.clone().into();
206 Ok(Activity::insert(pool, ap_id, activity, local, Some(sensitive)).await?)
209 /// Common methods provided by ActivityPub actors (community and person). Not all methods are
210 /// implemented by all actors.
211 pub trait ActorType: Actor + ApubObject {
212 fn actor_id(&self) -> Url;
214 fn private_key(&self) -> Option<String>;
216 fn get_public_key(&self) -> PublicKey {
217 PublicKey::new_main_key(self.actor_id(), self.public_key().to_string())
221 #[async_trait::async_trait(?Send)]
222 pub trait SendActivity {
225 async fn send_activity(
227 _response: &Self::Response,
228 _context: &LemmyContext,
229 ) -> Result<(), LemmyError> {