]> Untitled Git - lemmy.git/blob - crates/apub/src/objects/instance.rs
Fix limit_languages to operate on correct instance (fixes #2496) (#2518)
[lemmy.git] / crates / apub / src / objects / instance.rs
1 use crate::{
2   check_apub_id_valid_with_strictness,
3   fetch_local_site_data,
4   local_instance,
5   objects::read_from_string_or_source_opt,
6   protocol::{
7     objects::{
8       instance::{Instance, InstanceType},
9       LanguageTag,
10     },
11     ImageObject,
12     Source,
13   },
14   ActorType,
15 };
16 use activitypub_federation::{
17   core::object_id::ObjectId,
18   deser::values::MediaTypeHtml,
19   traits::{Actor, ApubObject},
20   utils::verify_domains_match,
21 };
22 use chrono::NaiveDateTime;
23 use lemmy_api_common::utils::{blocking, local_site_opt_to_slur_regex};
24 use lemmy_db_schema::{
25   source::{
26     actor_language::SiteLanguage,
27     instance::Instance as DbInstance,
28     site::{Site, SiteInsertForm},
29   },
30   traits::Crud,
31   utils::{naive_now, DbPool},
32 };
33 use lemmy_utils::{
34   error::LemmyError,
35   utils::{check_slurs, check_slurs_opt, convert_datetime, markdown_to_html},
36 };
37 use lemmy_websocket::LemmyContext;
38 use std::ops::Deref;
39 use tracing::debug;
40 use url::Url;
41
42 #[derive(Clone, Debug)]
43 pub struct ApubSite(Site);
44
45 impl Deref for ApubSite {
46   type Target = Site;
47   fn deref(&self) -> &Self::Target {
48     &self.0
49   }
50 }
51
52 impl From<Site> for ApubSite {
53   fn from(s: Site) -> Self {
54     ApubSite(s)
55   }
56 }
57
58 #[async_trait::async_trait(?Send)]
59 impl ApubObject for ApubSite {
60   type DataType = LemmyContext;
61   type ApubType = Instance;
62   type DbType = Site;
63   type Error = LemmyError;
64
65   fn last_refreshed_at(&self) -> Option<NaiveDateTime> {
66     Some(self.last_refreshed_at)
67   }
68
69   #[tracing::instrument(skip_all)]
70   async fn read_from_apub_id(
71     object_id: Url,
72     data: &Self::DataType,
73   ) -> Result<Option<Self>, LemmyError> {
74     Ok(
75       blocking(data.pool(), move |conn| {
76         Site::read_from_apub_id(conn, object_id)
77       })
78       .await??
79       .map(Into::into),
80     )
81   }
82
83   async fn delete(self, _data: &Self::DataType) -> Result<(), LemmyError> {
84     unimplemented!()
85   }
86
87   #[tracing::instrument(skip_all)]
88   async fn into_apub(self, data: &Self::DataType) -> Result<Self::ApubType, LemmyError> {
89     let site_id = self.id;
90     let langs = blocking(data.pool(), move |conn| SiteLanguage::read(conn, site_id)).await??;
91     let language = LanguageTag::new_multiple(langs, data.pool()).await?;
92
93     let instance = Instance {
94       kind: InstanceType::Service,
95       id: ObjectId::new(self.actor_id()),
96       name: self.name.clone(),
97       content: self.sidebar.as_ref().map(|d| markdown_to_html(d)),
98       source: self.sidebar.clone().map(Source::new),
99       summary: self.description.clone(),
100       media_type: self.sidebar.as_ref().map(|_| MediaTypeHtml::Html),
101       icon: self.icon.clone().map(ImageObject::new),
102       image: self.banner.clone().map(ImageObject::new),
103       inbox: self.inbox_url.clone().into(),
104       outbox: Url::parse(&format!("{}/site_outbox", self.actor_id))?,
105       public_key: self.get_public_key(),
106       language,
107       published: convert_datetime(self.published),
108       updated: self.updated.map(convert_datetime),
109     };
110     Ok(instance)
111   }
112
113   #[tracing::instrument(skip_all)]
114   async fn verify(
115     apub: &Self::ApubType,
116     expected_domain: &Url,
117     data: &Self::DataType,
118     _request_counter: &mut i32,
119   ) -> Result<(), LemmyError> {
120     let local_site_data = blocking(data.pool(), fetch_local_site_data).await??;
121
122     check_apub_id_valid_with_strictness(apub.id.inner(), true, &local_site_data, data.settings())?;
123     verify_domains_match(expected_domain, apub.id.inner())?;
124
125     let slur_regex = &local_site_opt_to_slur_regex(&local_site_data.local_site);
126
127     check_slurs(&apub.name, slur_regex)?;
128     check_slurs_opt(&apub.summary, slur_regex)?;
129     Ok(())
130   }
131
132   #[tracing::instrument(skip_all)]
133   async fn from_apub(
134     apub: Self::ApubType,
135     data: &Self::DataType,
136     _request_counter: &mut i32,
137   ) -> Result<Self, LemmyError> {
138     let apub_id = apub.id.inner().to_owned();
139     let instance = blocking(data.pool(), move |conn| {
140       DbInstance::create_from_actor_id(conn, &apub_id)
141     })
142     .await??;
143
144     let site_form = SiteInsertForm {
145       name: apub.name.clone(),
146       sidebar: read_from_string_or_source_opt(&apub.content, &None, &apub.source),
147       updated: apub.updated.map(|u| u.clone().naive_local()),
148       icon: apub.icon.clone().map(|i| i.url.into()),
149       banner: apub.image.clone().map(|i| i.url.into()),
150       description: apub.summary.clone(),
151       actor_id: Some(apub.id.clone().into()),
152       last_refreshed_at: Some(naive_now()),
153       inbox_url: Some(apub.inbox.clone().into()),
154       public_key: Some(apub.public_key.public_key_pem.clone()),
155       private_key: None,
156       instance_id: instance.id,
157     };
158     let languages = LanguageTag::to_language_id_multiple(apub.language, data.pool()).await?;
159
160     let site = blocking(data.pool(), move |conn| {
161       let site = Site::create(conn, &site_form)?;
162       SiteLanguage::update(conn, languages, &site)?;
163       Ok::<Site, diesel::result::Error>(site)
164     })
165     .await??;
166     Ok(site.into())
167   }
168 }
169
170 impl ActorType for ApubSite {
171   fn actor_id(&self) -> Url {
172     self.actor_id.to_owned().into()
173   }
174   fn private_key(&self) -> Option<String> {
175     self.private_key.to_owned()
176   }
177 }
178
179 impl Actor for ApubSite {
180   fn public_key(&self) -> &str {
181     &self.public_key
182   }
183
184   fn inbox(&self) -> Url {
185     self.inbox_url.clone().into()
186   }
187 }
188
189 /// Instance actor is at the root path, so we simply need to clear the path and other unnecessary
190 /// parts of the url.
191 pub fn instance_actor_id_from_url(mut url: Url) -> Url {
192   url.set_fragment(None);
193   url.set_path("");
194   url.set_query(None);
195   url
196 }
197
198 /// try to fetch the instance actor (to make things like instance rules available)
199 pub(in crate::objects) async fn fetch_instance_actor_for_object(
200   object_id: Url,
201   context: &LemmyContext,
202   request_counter: &mut i32,
203 ) {
204   // try to fetch the instance actor (to make things like instance rules available)
205   let instance_id = instance_actor_id_from_url(object_id);
206   let site = ObjectId::<ApubSite>::new(instance_id.clone())
207     .dereference(context, local_instance(context), request_counter)
208     .await;
209   if let Err(e) = site {
210     debug!("Failed to dereference site for {}: {}", instance_id, e);
211   }
212 }
213
214 pub(crate) async fn remote_instance_inboxes(pool: &DbPool) -> Result<Vec<Url>, LemmyError> {
215   Ok(
216     blocking(pool, Site::read_remote_sites)
217       .await??
218       .into_iter()
219       .map(|s| ApubSite::from(s).shared_inbox_or_inbox())
220       .collect(),
221   )
222 }
223
224 #[cfg(test)]
225 pub(crate) mod tests {
226   use super::*;
227   use crate::{objects::tests::init_context, protocol::tests::file_to_json_object};
228   use lemmy_db_schema::traits::Crud;
229   use serial_test::serial;
230
231   pub(crate) async fn parse_lemmy_instance(context: &LemmyContext) -> ApubSite {
232     let json: Instance = file_to_json_object("assets/lemmy/objects/instance.json").unwrap();
233     let id = Url::parse("https://enterprise.lemmy.ml/").unwrap();
234     let mut request_counter = 0;
235     ApubSite::verify(&json, &id, context, &mut request_counter)
236       .await
237       .unwrap();
238     let site = ApubSite::from_apub(json, context, &mut request_counter)
239       .await
240       .unwrap();
241     assert_eq!(request_counter, 0);
242     site
243   }
244
245   #[actix_rt::test]
246   #[serial]
247   async fn test_parse_lemmy_instance() {
248     let context = init_context();
249     let conn = &mut context.pool().get().unwrap();
250     let site = parse_lemmy_instance(&context).await;
251
252     assert_eq!(site.name, "Enterprise");
253     assert_eq!(site.description.as_ref().unwrap().len(), 15);
254
255     Site::delete(conn, site.id).unwrap();
256   }
257 }