]> Untitled Git - lemmy.git/blob - crates/apub/src/objects/instance.rs
Check user accepted before sending jwt in password reset (fixes #2591) (#2597)
[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::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       Site::read_from_apub_id(data.pool(), object_id)
76         .await?
77         .map(Into::into),
78     )
79   }
80
81   async fn delete(self, _data: &Self::DataType) -> Result<(), LemmyError> {
82     unimplemented!()
83   }
84
85   #[tracing::instrument(skip_all)]
86   async fn into_apub(self, data: &Self::DataType) -> Result<Self::ApubType, LemmyError> {
87     let site_id = self.id;
88     let langs = SiteLanguage::read(data.pool(), site_id).await?;
89     let language = LanguageTag::new_multiple(langs, data.pool()).await?;
90
91     let instance = Instance {
92       kind: InstanceType::Service,
93       id: ObjectId::new(self.actor_id()),
94       name: self.name.clone(),
95       content: self.sidebar.as_ref().map(|d| markdown_to_html(d)),
96       source: self.sidebar.clone().map(Source::new),
97       summary: self.description.clone(),
98       media_type: self.sidebar.as_ref().map(|_| MediaTypeHtml::Html),
99       icon: self.icon.clone().map(ImageObject::new),
100       image: self.banner.clone().map(ImageObject::new),
101       inbox: self.inbox_url.clone().into(),
102       outbox: Url::parse(&format!("{}/site_outbox", self.actor_id))?,
103       public_key: self.get_public_key(),
104       language,
105       published: convert_datetime(self.published),
106       updated: self.updated.map(convert_datetime),
107     };
108     Ok(instance)
109   }
110
111   #[tracing::instrument(skip_all)]
112   async fn verify(
113     apub: &Self::ApubType,
114     expected_domain: &Url,
115     data: &Self::DataType,
116     _request_counter: &mut i32,
117   ) -> Result<(), LemmyError> {
118     let local_site_data = fetch_local_site_data(data.pool()).await?;
119
120     check_apub_id_valid_with_strictness(apub.id.inner(), true, &local_site_data, data.settings())?;
121     verify_domains_match(expected_domain, apub.id.inner())?;
122
123     let slur_regex = &local_site_opt_to_slur_regex(&local_site_data.local_site);
124
125     check_slurs(&apub.name, slur_regex)?;
126     check_slurs_opt(&apub.summary, slur_regex)?;
127     Ok(())
128   }
129
130   #[tracing::instrument(skip_all)]
131   async fn from_apub(
132     apub: Self::ApubType,
133     data: &Self::DataType,
134     _request_counter: &mut i32,
135   ) -> Result<Self, LemmyError> {
136     let apub_id = apub.id.inner().clone();
137     let instance = DbInstance::create_from_actor_id(data.pool(), &apub_id).await?;
138
139     let site_form = SiteInsertForm {
140       name: apub.name.clone(),
141       sidebar: read_from_string_or_source_opt(&apub.content, &None, &apub.source),
142       updated: apub.updated.map(|u| u.clone().naive_local()),
143       icon: apub.icon.clone().map(|i| i.url.into()),
144       banner: apub.image.clone().map(|i| i.url.into()),
145       description: apub.summary.clone(),
146       actor_id: Some(apub.id.clone().into()),
147       last_refreshed_at: Some(naive_now()),
148       inbox_url: Some(apub.inbox.clone().into()),
149       public_key: Some(apub.public_key.public_key_pem.clone()),
150       private_key: None,
151       instance_id: instance.id,
152     };
153     let languages = LanguageTag::to_language_id_multiple(apub.language, data.pool()).await?;
154
155     let site = Site::create(data.pool(), &site_form).await?;
156     SiteLanguage::update(data.pool(), languages, &site).await?;
157     Ok(site.into())
158   }
159 }
160
161 impl ActorType for ApubSite {
162   fn actor_id(&self) -> Url {
163     self.actor_id.clone().into()
164   }
165   fn private_key(&self) -> Option<String> {
166     self.private_key.clone()
167   }
168 }
169
170 impl Actor for ApubSite {
171   fn public_key(&self) -> &str {
172     &self.public_key
173   }
174
175   fn inbox(&self) -> Url {
176     self.inbox_url.clone().into()
177   }
178 }
179
180 /// Instance actor is at the root path, so we simply need to clear the path and other unnecessary
181 /// parts of the url.
182 pub fn instance_actor_id_from_url(mut url: Url) -> Url {
183   url.set_fragment(None);
184   url.set_path("");
185   url.set_query(None);
186   url
187 }
188
189 /// try to fetch the instance actor (to make things like instance rules available)
190 pub(in crate::objects) async fn fetch_instance_actor_for_object(
191   object_id: Url,
192   context: &LemmyContext,
193   request_counter: &mut i32,
194 ) {
195   // try to fetch the instance actor (to make things like instance rules available)
196   let instance_id = instance_actor_id_from_url(object_id);
197   let site = ObjectId::<ApubSite>::new(instance_id.clone())
198     .dereference(context, local_instance(context).await, request_counter)
199     .await;
200   if let Err(e) = site {
201     debug!("Failed to dereference site for {}: {}", instance_id, e);
202   }
203 }
204
205 pub(crate) async fn remote_instance_inboxes(pool: &DbPool) -> Result<Vec<Url>, LemmyError> {
206   Ok(
207     Site::read_remote_sites(pool)
208       .await?
209       .into_iter()
210       .map(|s| ApubSite::from(s).shared_inbox_or_inbox())
211       .collect(),
212   )
213 }
214
215 #[cfg(test)]
216 pub(crate) mod tests {
217   use super::*;
218   use crate::{objects::tests::init_context, protocol::tests::file_to_json_object};
219   use lemmy_db_schema::traits::Crud;
220   use serial_test::serial;
221
222   pub(crate) async fn parse_lemmy_instance(context: &LemmyContext) -> ApubSite {
223     let json: Instance = file_to_json_object("assets/lemmy/objects/instance.json").unwrap();
224     let id = Url::parse("https://enterprise.lemmy.ml/").unwrap();
225     let mut request_counter = 0;
226     ApubSite::verify(&json, &id, context, &mut request_counter)
227       .await
228       .unwrap();
229     let site = ApubSite::from_apub(json, context, &mut request_counter)
230       .await
231       .unwrap();
232     assert_eq!(request_counter, 0);
233     site
234   }
235
236   #[actix_rt::test]
237   #[serial]
238   async fn test_parse_lemmy_instance() {
239     let context = init_context().await;
240     let site = parse_lemmy_instance(&context).await;
241
242     assert_eq!(site.name, "Enterprise");
243     assert_eq!(site.description.as_ref().unwrap().len(), 15);
244
245     Site::delete(context.pool(), site.id).await.unwrap();
246   }
247 }