1 use crate::fetcher::post_or_comment::PostOrComment;
2 use activitypub_federation::{
3 core::signatures::PublicKey,
4 traits::{Actor, ApubObject},
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 = InstanceSettings::builder()
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))
44 .http_signature_compat(true)
46 .expect("configure federation");
48 context.settings().hostname.to_owned(),
49 context.client().clone(),
55 /// Checks if the ID is allowed for sending or receiving.
57 /// In particular, it checks for:
58 /// - federation being enabled (if its disabled, only local URLs are allowed)
59 /// - the correct scheme (either http or https)
60 /// - URL being in the allowlist (if it is active)
61 /// - URL not being in the blocklist (if it is active)
63 /// `use_strict_allowlist` should be true only when parsing a remote community, or when parsing a
64 /// post/comment in a local community.
65 #[tracing::instrument(skip(settings))]
66 fn check_apub_id_valid(apub_id: &Url, settings: &Settings) -> Result<(), &'static str> {
67 let domain = apub_id.domain().expect("apud id has domain").to_string();
68 let local_instance = settings
69 .get_hostname_without_port()
70 .expect("local hostname is valid");
71 if domain == local_instance {
75 if !settings.federation.enabled {
76 return Err("Federation disabled");
79 if apub_id.scheme() != settings.get_protocol_string() {
80 return Err("Invalid protocol scheme");
83 if let Some(blocked) = settings.to_owned().federation.blocked_instances {
84 if blocked.contains(&domain) {
85 return Err("Domain is blocked");
89 if let Some(allowed) = settings.to_owned().federation.allowed_instances {
90 if !allowed.contains(&domain) {
91 return Err("Domain is not in allowlist");
98 #[tracing::instrument(skip(settings))]
99 pub(crate) fn check_apub_id_valid_with_strictness(
103 ) -> Result<(), LemmyError> {
104 check_apub_id_valid(apub_id, settings).map_err(LemmyError::from_message)?;
105 let domain = apub_id.domain().expect("apud id has domain").to_string();
106 let local_instance = settings
107 .get_hostname_without_port()
108 .expect("local hostname is valid");
109 if domain == local_instance {
113 if let Some(mut allowed) = settings.to_owned().federation.allowed_instances {
114 // Only check allowlist if this is a community, or strict allowlist is enabled.
115 let strict_allowlist = settings.to_owned().federation.strict_allowlist;
116 if is_strict || strict_allowlist {
117 // need to allow this explicitly because apub receive might contain objects from our local
119 allowed.push(local_instance);
121 if !allowed.contains(&domain) {
122 return Err(LemmyError::from_message(
123 "Federation forbidden by strict allowlist",
131 pub enum EndpointType {
139 /// Generates an apub endpoint for a given domain, IE xyz.tld
140 pub fn generate_local_apub_endpoint(
141 endpoint_type: EndpointType,
144 ) -> Result<DbUrl, ParseError> {
145 let point = match endpoint_type {
146 EndpointType::Community => "c",
147 EndpointType::Person => "u",
148 EndpointType::Post => "post",
149 EndpointType::Comment => "comment",
150 EndpointType::PrivateMessage => "private_message",
153 Ok(Url::parse(&format!("{}/{}/{}", domain, point, name))?.into())
156 pub fn generate_followers_url(actor_id: &DbUrl) -> Result<DbUrl, ParseError> {
157 Ok(Url::parse(&format!("{}/followers", actor_id))?.into())
160 pub fn generate_inbox_url(actor_id: &DbUrl) -> Result<DbUrl, ParseError> {
161 Ok(Url::parse(&format!("{}/inbox", actor_id))?.into())
164 pub fn generate_site_inbox_url(actor_id: &DbUrl) -> Result<DbUrl, ParseError> {
165 let mut actor_id: Url = actor_id.clone().into();
166 actor_id.set_path("site_inbox");
170 pub fn generate_shared_inbox_url(actor_id: &DbUrl) -> Result<DbUrl, LemmyError> {
171 let actor_id: Url = actor_id.clone().into();
175 &actor_id.host_str().context(location_info!())?,
176 if let Some(port) = actor_id.port() {
182 Ok(Url::parse(&url)?.into())
185 pub fn generate_outbox_url(actor_id: &DbUrl) -> Result<DbUrl, ParseError> {
186 Ok(Url::parse(&format!("{}/outbox", actor_id))?.into())
189 fn generate_moderators_url(community_id: &DbUrl) -> Result<DbUrl, LemmyError> {
190 Ok(Url::parse(&format!("{}/moderators", community_id))?.into())
193 /// Store a sent or received activity in the database, for logging purposes. These records are not
195 #[tracing::instrument(skip(pool))]
196 async fn insert_activity(
198 activity: serde_json::Value,
202 ) -> Result<bool, LemmyError> {
203 let ap_id = ap_id.to_owned().into();
205 blocking(pool, move |conn| {
206 Activity::insert(conn, ap_id, activity, local, sensitive)
212 /// Common methods provided by ActivityPub actors (community and person). Not all methods are
213 /// implemented by all actors.
214 pub trait ActorType: Actor + ApubObject {
215 fn actor_id(&self) -> Url;
217 fn private_key(&self) -> Option<String>;
219 fn get_public_key(&self) -> PublicKey {
220 PublicKey::new_main_key(self.actor_id(), self.public_key().to_string())