]> Untitled Git - lemmy.git/blob - crates/apub/src/lib.rs
b594acad5b2d6ed83cb685669bf51b4cf5411409
[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   InstanceSettings,
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::{
12   error::LemmyError,
13   location_info,
14   settings::{structs::Settings, SETTINGS},
15 };
16 use lemmy_websocket::LemmyContext;
17 use once_cell::sync::{Lazy, OnceCell};
18 use url::{ParseError, Url};
19
20 pub mod activities;
21 pub(crate) mod activity_lists;
22 pub(crate) mod collections;
23 pub mod fetcher;
24 pub mod http;
25 pub(crate) mod mentions;
26 pub mod objects;
27 pub mod protocol;
28
29 static CONTEXT: Lazy<Vec<serde_json::Value>> = Lazy::new(|| {
30   serde_json::from_str(include_str!("../assets/lemmy/context.json")).expect("parse context")
31 });
32
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)
45       .build()
46       .expect("configure federation");
47     LocalInstance::new(
48       context.settings().hostname.to_owned(),
49       context.client().clone(),
50       settings,
51     )
52   })
53 }
54
55 /// Checks if the ID is allowed for sending or receiving.
56 ///
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)
62 ///
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 {
72     return Ok(());
73   }
74
75   if !settings.federation.enabled {
76     return Err("Federation disabled");
77   }
78
79   if apub_id.scheme() != settings.get_protocol_string() {
80     return Err("Invalid protocol scheme");
81   }
82
83   if let Some(blocked) = settings.to_owned().federation.blocked_instances {
84     if blocked.contains(&domain) {
85       return Err("Domain is blocked");
86     }
87   }
88
89   if let Some(allowed) = settings.to_owned().federation.allowed_instances {
90     if !allowed.contains(&domain) {
91       return Err("Domain is not in allowlist");
92     }
93   }
94
95   Ok(())
96 }
97
98 #[tracing::instrument(skip(settings))]
99 pub(crate) fn check_apub_id_valid_with_strictness(
100   apub_id: &Url,
101   is_strict: bool,
102   settings: &Settings,
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 {
110     return Ok(());
111   }
112
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
118       // instance.
119       allowed.push(local_instance);
120
121       if !allowed.contains(&domain) {
122         return Err(LemmyError::from_message(
123           "Federation forbidden by strict allowlist",
124         ));
125       }
126     }
127   }
128   Ok(())
129 }
130
131 pub enum EndpointType {
132   Community,
133   Person,
134   Post,
135   Comment,
136   PrivateMessage,
137 }
138
139 /// Generates an apub endpoint for a given domain, IE xyz.tld
140 pub fn generate_local_apub_endpoint(
141   endpoint_type: EndpointType,
142   name: &str,
143   domain: &str,
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",
151   };
152
153   Ok(Url::parse(&format!("{}/{}/{}", domain, point, name))?.into())
154 }
155
156 pub fn generate_followers_url(actor_id: &DbUrl) -> Result<DbUrl, ParseError> {
157   Ok(Url::parse(&format!("{}/followers", actor_id))?.into())
158 }
159
160 pub fn generate_inbox_url(actor_id: &DbUrl) -> Result<DbUrl, ParseError> {
161   Ok(Url::parse(&format!("{}/inbox", actor_id))?.into())
162 }
163
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");
167   Ok(actor_id.into())
168 }
169
170 pub fn generate_shared_inbox_url(actor_id: &DbUrl) -> Result<DbUrl, LemmyError> {
171   let actor_id: Url = actor_id.clone().into();
172   let url = format!(
173     "{}://{}{}/inbox",
174     &actor_id.scheme(),
175     &actor_id.host_str().context(location_info!())?,
176     if let Some(port) = actor_id.port() {
177       format!(":{}", port)
178     } else {
179       "".to_string()
180     },
181   );
182   Ok(Url::parse(&url)?.into())
183 }
184
185 pub fn generate_outbox_url(actor_id: &DbUrl) -> Result<DbUrl, ParseError> {
186   Ok(Url::parse(&format!("{}/outbox", actor_id))?.into())
187 }
188
189 fn generate_moderators_url(community_id: &DbUrl) -> Result<DbUrl, LemmyError> {
190   Ok(Url::parse(&format!("{}/moderators", community_id))?.into())
191 }
192
193 /// Store a sent or received activity in the database, for logging purposes. These records are not
194 /// persistent.
195 #[tracing::instrument(skip(pool))]
196 async fn insert_activity(
197   ap_id: &Url,
198   activity: serde_json::Value,
199   local: bool,
200   sensitive: bool,
201   pool: &DbPool,
202 ) -> Result<bool, LemmyError> {
203   let ap_id = ap_id.to_owned().into();
204   Ok(
205     blocking(pool, move |conn| {
206       Activity::insert(conn, ap_id, activity, local, sensitive)
207     })
208     .await??,
209   )
210 }
211
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;
216
217   fn private_key(&self) -> Option<String>;
218
219   fn get_public_key(&self) -> PublicKey {
220     PublicKey::new_main_key(self.actor_id(), self.public_key().to_string())
221   }
222 }