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