1 use crate::fetcher::post_or_comment::PostOrComment;
2 use activitypub_federation::{
3 core::signatures::PublicKey,
4 traits::{Actor, ApubObject},
5 InstanceSettingsBuilder,
9 use lemmy_api_common::utils::blocking;
10 use lemmy_db_schema::{newtypes::DbUrl, source::activity::Activity, utils::DbPool};
14 settings::{structs::Settings, SETTINGS},
16 use lemmy_websocket::LemmyContext;
17 use once_cell::sync::{Lazy, OnceCell};
18 use url::{ParseError, Url};
21 pub(crate) mod activity_lists;
22 pub(crate) mod collections;
25 pub(crate) mod mentions;
29 static CONTEXT: Lazy<Vec<serde_json::Value>> = Lazy::new(|| {
30 serde_json::from_str(include_str!("../assets/lemmy/context.json")).expect("parse context")
33 // TODO: store this in context? but its only used in this crate, no need to expose it elsewhere
34 fn local_instance(context: &LemmyContext) -> &'static LocalInstance {
35 static LOCAL_INSTANCE: OnceCell<LocalInstance> = OnceCell::new();
36 LOCAL_INSTANCE.get_or_init(|| {
37 let settings = InstanceSettingsBuilder::default()
38 .http_fetch_retry_limit(context.settings().federation.http_fetch_retry_limit)
39 .worker_count(context.settings().federation.worker_count)
40 .debug(context.settings().federation.debug)
41 // TODO No idea why, but you can't pass context.settings() to the verify_url_function closure
42 // without the value getting captured.
43 .verify_url_function(|url| check_apub_id_valid(url, &SETTINGS))
45 .expect("configure federation");
47 context.settings().hostname.to_owned(),
48 context.client().clone(),
54 /// Checks if the ID is allowed for sending or receiving.
56 /// In particular, it checks for:
57 /// - federation being enabled (if its disabled, only local URLs are allowed)
58 /// - the correct scheme (either http or https)
59 /// - URL being in the allowlist (if it is active)
60 /// - URL not being in the blocklist (if it is active)
62 /// `use_strict_allowlist` should be true only when parsing a remote community, or when parsing a
63 /// post/comment in a local community.
64 #[tracing::instrument(skip(settings))]
65 fn check_apub_id_valid(apub_id: &Url, settings: &Settings) -> Result<(), &'static str> {
66 let domain = apub_id.domain().expect("apud id has domain").to_string();
67 let local_instance = settings
68 .get_hostname_without_port()
69 .expect("local hostname is valid");
70 if domain == local_instance {
74 if !settings.federation.enabled {
75 return Err("Federation disabled");
78 if apub_id.scheme() != settings.get_protocol_string() {
79 return Err("Invalid protocol scheme");
82 if let Some(blocked) = settings.to_owned().federation.blocked_instances {
83 if blocked.contains(&domain) {
84 return Err("Domain is blocked");
88 if let Some(allowed) = settings.to_owned().federation.allowed_instances {
89 if !allowed.contains(&domain) {
90 return Err("Domain is not in allowlist");
97 #[tracing::instrument(skip(settings))]
98 pub(crate) fn check_apub_id_valid_with_strictness(
102 ) -> Result<(), LemmyError> {
103 check_apub_id_valid(apub_id, settings).map_err(LemmyError::from_message)?;
104 let domain = apub_id.domain().expect("apud id has domain").to_string();
105 let local_instance = settings
106 .get_hostname_without_port()
107 .expect("local hostname is valid");
108 if domain == local_instance {
112 if let Some(mut allowed) = settings.to_owned().federation.allowed_instances {
113 // Only check allowlist if this is a community, or strict allowlist is enabled.
114 let strict_allowlist = settings.to_owned().federation.strict_allowlist;
115 if is_strict || strict_allowlist {
116 // need to allow this explicitly because apub receive might contain objects from our local
118 allowed.push(local_instance);
120 if !allowed.contains(&domain) {
121 return Err(LemmyError::from_message(
122 "Federation forbidden by strict allowlist",
130 pub enum EndpointType {
138 /// Generates an apub endpoint for a given domain, IE xyz.tld
139 pub fn generate_local_apub_endpoint(
140 endpoint_type: EndpointType,
143 ) -> Result<DbUrl, ParseError> {
144 let point = match endpoint_type {
145 EndpointType::Community => "c",
146 EndpointType::Person => "u",
147 EndpointType::Post => "post",
148 EndpointType::Comment => "comment",
149 EndpointType::PrivateMessage => "private_message",
152 Ok(Url::parse(&format!("{}/{}/{}", domain, point, name))?.into())
155 pub fn generate_followers_url(actor_id: &DbUrl) -> Result<DbUrl, ParseError> {
156 Ok(Url::parse(&format!("{}/followers", actor_id))?.into())
159 pub fn generate_inbox_url(actor_id: &DbUrl) -> Result<DbUrl, ParseError> {
160 Ok(Url::parse(&format!("{}/inbox", actor_id))?.into())
163 pub fn generate_site_inbox_url(actor_id: &DbUrl) -> Result<DbUrl, ParseError> {
164 let mut actor_id: Url = actor_id.clone().into();
165 actor_id.set_path("site_inbox");
169 pub fn generate_shared_inbox_url(actor_id: &DbUrl) -> Result<DbUrl, LemmyError> {
170 let actor_id: Url = actor_id.clone().into();
174 &actor_id.host_str().context(location_info!())?,
175 if let Some(port) = actor_id.port() {
181 Ok(Url::parse(&url)?.into())
184 pub fn generate_outbox_url(actor_id: &DbUrl) -> Result<DbUrl, ParseError> {
185 Ok(Url::parse(&format!("{}/outbox", actor_id))?.into())
188 fn generate_moderators_url(community_id: &DbUrl) -> Result<DbUrl, LemmyError> {
189 Ok(Url::parse(&format!("{}/moderators", community_id))?.into())
192 /// Store a sent or received activity in the database, for logging purposes. These records are not
194 #[tracing::instrument(skip(pool))]
195 async fn insert_activity(
197 activity: serde_json::Value,
201 ) -> Result<bool, LemmyError> {
202 let ap_id = ap_id.to_owned().into();
204 blocking(pool, move |conn| {
205 Activity::insert(conn, ap_id, activity, local, sensitive)
211 /// Common methods provided by ActivityPub actors (community and person). Not all methods are
212 /// implemented by all actors.
213 pub trait ActorType: Actor + ApubObject {
214 fn actor_id(&self) -> Url;
216 fn private_key(&self) -> Option<String>;
218 fn get_public_key(&self) -> PublicKey {
219 PublicKey::new_main_key(self.actor_id(), self.public_key().to_string())