1 use crate::fetcher::post_or_comment::PostOrComment;
2 use activitypub_federation::{
3 core::signatures::PublicKey,
4 traits::{Actor, ApubObject},
9 use diesel::PgConnection;
10 use lemmy_api_common::utils::blocking;
11 use lemmy_db_schema::{
13 source::{activity::Activity, instance::Instance, local_site::LocalSite},
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};
22 pub(crate) mod activity_lists;
23 pub(crate) mod collections;
26 pub(crate) mod mentions;
30 static CONTEXT: Lazy<Vec<serde_json::Value>> = Lazy::new(|| {
31 serde_json::from_str(include_str!("../assets/lemmy/context.json")).expect("parse context")
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
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
47 .map(|l| l.federation_worker_count)
48 .unwrap_or(64) as u64;
49 let http_fetch_retry_limit = local_site
51 .map(|l| l.federation_http_fetch_retry_limit)
53 let federation_debug = local_site
55 .map(|l| l.federation_debug)
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)
66 .expect("configure federation");
68 context.settings().hostname.to_owned(),
69 context.client().clone(),
75 /// Checks if the ID is allowed for sending or receiving.
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)
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(
89 local_site_data: &LocalSiteData,
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 {
103 .map(|l| l.federation_enabled)
106 return Err("Federation disabled");
109 if apub_id.scheme() != settings.get_protocol_string() {
110 return Err("Invalid protocol scheme");
113 if let Some(blocked) = local_site_data.blocked_instances.as_ref() {
114 if blocked.contains(&domain) {
115 return Err("Domain is blocked");
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");
129 pub(crate) struct LocalSiteData {
130 local_site: Option<LocalSite>,
131 allowed_instances: Option<Vec<String>>,
132 blocked_instances: Option<Vec<String>>,
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)?;
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);
154 #[tracing::instrument(skip(settings, local_site_data))]
155 pub(crate) fn check_apub_id_valid_with_strictness(
158 local_site_data: &LocalSiteData,
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 {
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
175 .map(|l| l.federation_strict_allowlist)
177 if is_strict || strict_allowlist {
178 // need to allow this explicitly because apub receive might contain objects from our local
180 let mut allowed_and_local = allowed.to_owned();
181 allowed_and_local.push(local_instance);
183 if !allowed_and_local.contains(&domain) {
184 return Err(LemmyError::from_message(
185 "Federation forbidden by strict allowlist",
193 pub enum EndpointType {
201 /// Generates an apub endpoint for a given domain, IE xyz.tld
202 pub fn generate_local_apub_endpoint(
203 endpoint_type: EndpointType,
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",
215 Ok(Url::parse(&format!("{}/{}/{}", domain, point, name))?.into())
218 pub fn generate_followers_url(actor_id: &DbUrl) -> Result<DbUrl, ParseError> {
219 Ok(Url::parse(&format!("{}/followers", actor_id))?.into())
222 pub fn generate_inbox_url(actor_id: &DbUrl) -> Result<DbUrl, ParseError> {
223 Ok(Url::parse(&format!("{}/inbox", actor_id))?.into())
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");
232 pub fn generate_shared_inbox_url(actor_id: &DbUrl) -> Result<DbUrl, LemmyError> {
233 let actor_id: Url = actor_id.clone().into();
237 &actor_id.host_str().context(location_info!())?,
238 if let Some(port) = actor_id.port() {
244 Ok(Url::parse(&url)?.into())
247 pub fn generate_outbox_url(actor_id: &DbUrl) -> Result<DbUrl, ParseError> {
248 Ok(Url::parse(&format!("{}/outbox", actor_id))?.into())
251 fn generate_moderators_url(community_id: &DbUrl) -> Result<DbUrl, LemmyError> {
252 Ok(Url::parse(&format!("{}/moderators", community_id))?.into())
255 /// Store a sent or received activity in the database, for logging purposes. These records are not
257 #[tracing::instrument(skip(pool))]
258 async fn insert_activity(
260 activity: serde_json::Value,
264 ) -> Result<bool, LemmyError> {
265 let ap_id = ap_id.to_owned().into();
267 blocking(pool, move |conn| {
268 Activity::insert(conn, ap_id, activity, local, Some(sensitive))
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;
279 fn private_key(&self) -> Option<String>;
281 fn get_public_key(&self) -> PublicKey {
282 PublicKey::new_main_key(self.actor_id(), self.public_key().to_string())