]> Untitled Git - lemmy.git/blob - crates/apub/src/lib.rs
Move setting http_fetch_retry_limit into federation block (#2314)
[lemmy.git] / crates / apub / src / lib.rs
1 use crate::fetcher::post_or_comment::PostOrComment;
2 use activitypub_federation::{
3   core::signatures::PublicKey,
4   traits::{Actor, ApubObject},
5   InstanceSettingsBuilder,
6   LocalInstance,
7 };
8 use anyhow::Context;
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};
15
16 pub mod activities;
17 pub(crate) mod activity_lists;
18 pub(crate) mod collections;
19 pub mod fetcher;
20 pub mod http;
21 pub(crate) mod mentions;
22 pub mod objects;
23 pub mod protocol;
24
25 static CONTEXT: Lazy<Vec<serde_json::Value>> = Lazy::new(|| {
26   serde_json::from_str(include_str!("../assets/lemmy/context.json")).expect("parse context")
27 });
28
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().federation.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()))
38       .build()
39       .expect("configure federation");
40     LocalInstance::new(
41       context.settings().hostname,
42       context.client().clone(),
43       settings,
44     )
45   })
46 }
47
48 /// Checks if the ID is allowed for sending or receiving.
49 ///
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)
55 ///
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 {
65     return Ok(());
66   }
67
68   if !settings.federation.enabled {
69     return Err("Federation disabled");
70   }
71
72   if apub_id.scheme() != settings.get_protocol_string() {
73     return Err("Invalid protocol scheme");
74   }
75
76   if let Some(blocked) = settings.to_owned().federation.blocked_instances {
77     if blocked.contains(&domain) {
78       return Err("Domain is blocked");
79     }
80   }
81
82   if let Some(allowed) = settings.to_owned().federation.allowed_instances {
83     if !allowed.contains(&domain) {
84       return Err("Domain is not in allowlist");
85     }
86   }
87
88   Ok(())
89 }
90
91 #[tracing::instrument(skip(settings))]
92 pub(crate) fn check_apub_id_valid_with_strictness(
93   apub_id: &Url,
94   is_strict: bool,
95   settings: &Settings,
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 {
103     return Ok(());
104   }
105
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
111       // instance.
112       allowed.push(local_instance);
113
114       if !allowed.contains(&domain) {
115         return Err(LemmyError::from_message(
116           "Federation forbidden by strict allowlist",
117         ));
118       }
119     }
120   }
121   Ok(())
122 }
123
124 pub enum EndpointType {
125   Community,
126   Person,
127   Post,
128   Comment,
129   PrivateMessage,
130 }
131
132 /// Generates an apub endpoint for a given domain, IE xyz.tld
133 pub fn generate_local_apub_endpoint(
134   endpoint_type: EndpointType,
135   name: &str,
136   domain: &str,
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",
144   };
145
146   Ok(Url::parse(&format!("{}/{}/{}", domain, point, name))?.into())
147 }
148
149 pub fn generate_followers_url(actor_id: &DbUrl) -> Result<DbUrl, ParseError> {
150   Ok(Url::parse(&format!("{}/followers", actor_id))?.into())
151 }
152
153 pub fn generate_inbox_url(actor_id: &DbUrl) -> Result<DbUrl, ParseError> {
154   Ok(Url::parse(&format!("{}/inbox", actor_id))?.into())
155 }
156
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");
160   Ok(actor_id.into())
161 }
162
163 pub fn generate_shared_inbox_url(actor_id: &DbUrl) -> Result<DbUrl, LemmyError> {
164   let actor_id: Url = actor_id.clone().into();
165   let url = format!(
166     "{}://{}{}/inbox",
167     &actor_id.scheme(),
168     &actor_id.host_str().context(location_info!())?,
169     if let Some(port) = actor_id.port() {
170       format!(":{}", port)
171     } else {
172       "".to_string()
173     },
174   );
175   Ok(Url::parse(&url)?.into())
176 }
177
178 pub fn generate_outbox_url(actor_id: &DbUrl) -> Result<DbUrl, ParseError> {
179   Ok(Url::parse(&format!("{}/outbox", actor_id))?.into())
180 }
181
182 fn generate_moderators_url(community_id: &DbUrl) -> Result<DbUrl, LemmyError> {
183   Ok(Url::parse(&format!("{}/moderators", community_id))?.into())
184 }
185
186 /// Store a sent or received activity in the database, for logging purposes. These records are not
187 /// persistent.
188 #[tracing::instrument(skip(pool))]
189 async fn insert_activity(
190   ap_id: &Url,
191   activity: serde_json::Value,
192   local: bool,
193   sensitive: bool,
194   pool: &DbPool,
195 ) -> Result<bool, LemmyError> {
196   let ap_id = ap_id.to_owned().into();
197   Ok(
198     blocking(pool, move |conn| {
199       Activity::insert(conn, ap_id, activity, local, sensitive)
200     })
201     .await??,
202   )
203 }
204
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;
209
210   fn private_key(&self) -> Option<String>;
211
212   fn get_public_key(&self) -> PublicKey {
213     PublicKey::new_main_key(self.actor_id(), self.public_key().to_string())
214   }
215 }