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};
11 use lemmy_utils::{error::LemmyError, location_info, settings::structs::Settings};
12 use lemmy_websocket::LemmyContext;
13 use once_cell::sync::{Lazy, OnceCell};
14 use url::{ParseError, Url};
17 pub(crate) mod activity_lists;
18 pub(crate) mod collections;
21 pub(crate) mod mentions;
25 static CONTEXT: Lazy<Vec<serde_json::Value>> = Lazy::new(|| {
26 serde_json::from_str(include_str!("../assets/lemmy/context.json")).expect("parse context")
29 // TODO: store this in context? but its only used in this crate, no need to expose it elsewhere
30 fn local_instance(context: &LemmyContext) -> &'static LocalInstance {
31 static LOCAL_INSTANCE: OnceCell<LocalInstance> = OnceCell::new();
32 LOCAL_INSTANCE.get_or_init(|| {
33 let settings = InstanceSettingsBuilder::default()
34 .http_fetch_retry_limit(context.settings().http_fetch_retry_limit)
35 .worker_count(context.settings().federation.worker_count)
36 .debug(context.settings().federation.debug)
37 .verify_url_function(|url| check_apub_id_valid(url, &Settings::get()))
39 .expect("configure federation");
41 context.settings().hostname,
42 context.client().clone(),
48 /// Checks if the ID is allowed for sending or receiving.
50 /// In particular, it checks for:
51 /// - federation being enabled (if its disabled, only local URLs are allowed)
52 /// - the correct scheme (either http or https)
53 /// - URL being in the allowlist (if it is active)
54 /// - URL not being in the blocklist (if it is active)
56 /// `use_strict_allowlist` should be true only when parsing a remote community, or when parsing a
57 /// post/comment in a local community.
58 #[tracing::instrument(skip(settings))]
59 fn check_apub_id_valid(apub_id: &Url, settings: &Settings) -> Result<(), &'static str> {
60 let domain = apub_id.domain().expect("apud id has domain").to_string();
61 let local_instance = settings
62 .get_hostname_without_port()
63 .expect("local hostname is valid");
64 if domain == local_instance {
68 if !settings.federation.enabled {
69 return Err("Federation disabled");
72 if apub_id.scheme() != settings.get_protocol_string() {
73 return Err("Invalid protocol scheme");
76 if let Some(blocked) = settings.to_owned().federation.blocked_instances {
77 if blocked.contains(&domain) {
78 return Err("Domain is blocked");
82 if let Some(allowed) = settings.to_owned().federation.allowed_instances {
83 if !allowed.contains(&domain) {
84 return Err("Domain is not in allowlist");
91 #[tracing::instrument(skip(settings))]
92 pub(crate) fn check_apub_id_valid_with_strictness(
96 ) -> Result<(), LemmyError> {
97 check_apub_id_valid(apub_id, settings).map_err(LemmyError::from_message)?;
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 {
106 if let Some(mut allowed) = settings.to_owned().federation.allowed_instances {
107 // Only check allowlist if this is a community, or strict allowlist is enabled.
108 let strict_allowlist = settings.to_owned().federation.strict_allowlist;
109 if is_strict || strict_allowlist {
110 // need to allow this explicitly because apub receive might contain objects from our local
112 allowed.push(local_instance);
114 if !allowed.contains(&domain) {
115 return Err(LemmyError::from_message(
116 "Federation forbidden by strict allowlist",
124 pub enum EndpointType {
132 /// Generates an apub endpoint for a given domain, IE xyz.tld
133 pub fn generate_local_apub_endpoint(
134 endpoint_type: EndpointType,
137 ) -> Result<DbUrl, ParseError> {
138 let point = match endpoint_type {
139 EndpointType::Community => "c",
140 EndpointType::Person => "u",
141 EndpointType::Post => "post",
142 EndpointType::Comment => "comment",
143 EndpointType::PrivateMessage => "private_message",
146 Ok(Url::parse(&format!("{}/{}/{}", domain, point, name))?.into())
149 pub fn generate_followers_url(actor_id: &DbUrl) -> Result<DbUrl, ParseError> {
150 Ok(Url::parse(&format!("{}/followers", actor_id))?.into())
153 pub fn generate_inbox_url(actor_id: &DbUrl) -> Result<DbUrl, ParseError> {
154 Ok(Url::parse(&format!("{}/inbox", actor_id))?.into())
157 pub fn generate_site_inbox_url(actor_id: &DbUrl) -> Result<DbUrl, ParseError> {
158 let mut actor_id: Url = actor_id.clone().into();
159 actor_id.set_path("site_inbox");
163 pub fn generate_shared_inbox_url(actor_id: &DbUrl) -> Result<DbUrl, LemmyError> {
164 let actor_id: Url = actor_id.clone().into();
168 &actor_id.host_str().context(location_info!())?,
169 if let Some(port) = actor_id.port() {
175 Ok(Url::parse(&url)?.into())
178 pub fn generate_outbox_url(actor_id: &DbUrl) -> Result<DbUrl, ParseError> {
179 Ok(Url::parse(&format!("{}/outbox", actor_id))?.into())
182 fn generate_moderators_url(community_id: &DbUrl) -> Result<DbUrl, LemmyError> {
183 Ok(Url::parse(&format!("{}/moderators", community_id))?.into())
186 /// Store a sent or received activity in the database, for logging purposes. These records are not
188 #[tracing::instrument(skip(pool))]
189 async fn insert_activity(
191 activity: serde_json::Value,
195 ) -> Result<bool, LemmyError> {
196 let ap_id = ap_id.to_owned().into();
198 blocking(pool, move |conn| {
199 Activity::insert(conn, ap_id, activity, local, sensitive)
205 /// Common methods provided by ActivityPub actors (community and person). Not all methods are
206 /// implemented by all actors.
207 pub trait ActorType: Actor + ApubObject {
208 fn actor_id(&self) -> Url;
210 fn private_key(&self) -> Option<String>;
212 fn get_public_key(&self) -> PublicKey {
213 PublicKey::new_main_key(self.actor_id(), self.public_key().to_string())