]> Untitled Git - lemmy.git/blob - crates/apub/src/objects/post.rs
Sanitize html (#3708)
[lemmy.git] / crates / apub / src / objects / post.rs
1 use crate::{
2   activities::{verify_is_public, verify_person_in_community},
3   check_apub_id_valid_with_strictness,
4   local_site_data_cached,
5   objects::{read_from_string_or_source_opt, verify_is_remote_object},
6   protocol::{
7     objects::{
8       page::{Attachment, AttributedTo, Page, PageType},
9       LanguageTag,
10     },
11     ImageObject,
12     InCommunity,
13     Source,
14   },
15 };
16 use activitypub_federation::{
17   config::Data,
18   kinds::public,
19   protocol::{values::MediaTypeMarkdownOrHtml, verification::verify_domains_match},
20   traits::Object,
21 };
22 use anyhow::anyhow;
23 use chrono::NaiveDateTime;
24 use html2md::parse_html;
25 use lemmy_api_common::{
26   context::LemmyContext,
27   request::fetch_site_data,
28   utils::{
29     is_mod_or_admin,
30     local_site_opt_to_sensitive,
31     local_site_opt_to_slur_regex,
32     sanitize_html,
33     sanitize_html_opt,
34   },
35 };
36 use lemmy_db_schema::{
37   self,
38   source::{
39     community::Community,
40     local_site::LocalSite,
41     moderator::{ModLockPost, ModLockPostForm},
42     person::Person,
43     post::{Post, PostInsertForm, PostUpdateForm},
44   },
45   traits::Crud,
46 };
47 use lemmy_utils::{
48   error::LemmyError,
49   utils::{
50     markdown::markdown_to_html,
51     slurs::{check_slurs_opt, remove_slurs},
52     time::convert_datetime,
53     validation::check_url_scheme,
54   },
55 };
56 use std::ops::Deref;
57 use url::Url;
58
59 const MAX_TITLE_LENGTH: usize = 200;
60
61 #[derive(Clone, Debug)]
62 pub struct ApubPost(pub(crate) Post);
63
64 impl Deref for ApubPost {
65   type Target = Post;
66   fn deref(&self) -> &Self::Target {
67     &self.0
68   }
69 }
70
71 impl From<Post> for ApubPost {
72   fn from(p: Post) -> Self {
73     ApubPost(p)
74   }
75 }
76
77 #[async_trait::async_trait]
78 impl Object for ApubPost {
79   type DataType = LemmyContext;
80   type Kind = Page;
81   type Error = LemmyError;
82
83   fn last_refreshed_at(&self) -> Option<NaiveDateTime> {
84     None
85   }
86
87   #[tracing::instrument(skip_all)]
88   async fn read_from_id(
89     object_id: Url,
90     context: &Data<Self::DataType>,
91   ) -> Result<Option<Self>, LemmyError> {
92     Ok(
93       Post::read_from_apub_id(&mut context.pool(), object_id)
94         .await?
95         .map(Into::into),
96     )
97   }
98
99   #[tracing::instrument(skip_all)]
100   async fn delete(self, context: &Data<Self::DataType>) -> Result<(), LemmyError> {
101     if !self.deleted {
102       let form = PostUpdateForm::builder().deleted(Some(true)).build();
103       Post::update(&mut context.pool(), self.id, &form).await?;
104     }
105     Ok(())
106   }
107
108   // Turn a Lemmy post into an ActivityPub page that can be sent out over the network.
109   #[tracing::instrument(skip_all)]
110   async fn into_json(self, context: &Data<Self::DataType>) -> Result<Page, LemmyError> {
111     let creator_id = self.creator_id;
112     let creator = Person::read(&mut context.pool(), creator_id).await?;
113     let community_id = self.community_id;
114     let community = Community::read(&mut context.pool(), community_id).await?;
115     let language = LanguageTag::new_single(self.language_id, &mut context.pool()).await?;
116
117     let page = Page {
118       kind: PageType::Page,
119       id: self.ap_id.clone().into(),
120       attributed_to: AttributedTo::Lemmy(creator.actor_id.into()),
121       to: vec![community.actor_id.clone().into(), public()],
122       cc: vec![],
123       name: Some(self.name.clone()),
124       content: self.body.as_ref().map(|b| markdown_to_html(b)),
125       media_type: Some(MediaTypeMarkdownOrHtml::Html),
126       source: self.body.clone().map(Source::new),
127       attachment: self.url.clone().map(Attachment::new).into_iter().collect(),
128       image: self.thumbnail_url.clone().map(ImageObject::new),
129       comments_enabled: Some(!self.locked),
130       sensitive: Some(self.nsfw),
131       language,
132       published: Some(convert_datetime(self.published)),
133       updated: self.updated.map(convert_datetime),
134       audience: Some(community.actor_id.into()),
135       in_reply_to: None,
136     };
137     Ok(page)
138   }
139
140   #[tracing::instrument(skip_all)]
141   async fn verify(
142     page: &Page,
143     expected_domain: &Url,
144     context: &Data<Self::DataType>,
145   ) -> Result<(), LemmyError> {
146     // We can't verify the domain in case of mod action, because the mod may be on a different
147     // instance from the post author.
148     if !page.is_mod_action(context).await? {
149       verify_domains_match(page.id.inner(), expected_domain)?;
150       verify_is_remote_object(page.id.inner(), context.settings())?;
151     };
152
153     let community = page.community(context).await?;
154     check_apub_id_valid_with_strictness(page.id.inner(), community.local, context).await?;
155     verify_person_in_community(&page.creator()?, &community, context).await?;
156
157     let local_site_data = local_site_data_cached(&mut context.pool()).await?;
158     let slur_regex = &local_site_opt_to_slur_regex(&local_site_data.local_site);
159     check_slurs_opt(&page.name, slur_regex)?;
160
161     verify_domains_match(page.creator()?.inner(), page.id.inner())?;
162     verify_is_public(&page.to, &page.cc)?;
163     Ok(())
164   }
165
166   #[tracing::instrument(skip_all)]
167   async fn from_json(page: Page, context: &Data<Self::DataType>) -> Result<ApubPost, LemmyError> {
168     let creator = page.creator()?.dereference(context).await?;
169     let community = page.community(context).await?;
170     if community.posting_restricted_to_mods {
171       is_mod_or_admin(&mut context.pool(), creator.id, community.id).await?;
172     }
173     let mut name = page
174       .name
175       .clone()
176       .or_else(|| {
177         page
178           .content
179           .clone()
180           .as_ref()
181           .and_then(|c| parse_html(c).lines().next().map(ToString::to_string))
182       })
183       .ok_or_else(|| anyhow!("Object must have name or content"))?;
184     if name.chars().count() > MAX_TITLE_LENGTH {
185       name = name.chars().take(MAX_TITLE_LENGTH).collect();
186     }
187
188     // read existing, local post if any (for generating mod log)
189     let old_post = page.id.dereference_local(context).await;
190
191     let form = if !page.is_mod_action(context).await? {
192       let first_attachment = page.attachment.into_iter().map(Attachment::url).next();
193       let url = if first_attachment.is_some() {
194         first_attachment
195       } else if page.kind == PageType::Video {
196         // we cant display videos directly, so insert a link to external video page
197         Some(page.id.inner().clone())
198       } else {
199         None
200       };
201       check_url_scheme(&url)?;
202
203       let local_site = LocalSite::read(&mut context.pool()).await.ok();
204       let allow_sensitive = local_site_opt_to_sensitive(&local_site);
205       let page_is_sensitive = page.sensitive.unwrap_or(false);
206       let include_image = allow_sensitive || !page_is_sensitive;
207
208       // Only fetch metadata if the post has a url and was not seen previously. We dont want to
209       // waste resources by fetching metadata for the same post multiple times.
210       // Additionally, only fetch image if content is not sensitive or is allowed on local site.
211       let (metadata_res, thumbnail) = match &url {
212         Some(url) if old_post.is_err() => {
213           fetch_site_data(
214             context.client(),
215             context.settings(),
216             Some(url),
217             include_image,
218           )
219           .await
220         }
221         _ => (None, None),
222       };
223       // If no image was included with metadata, use post image instead when available.
224       let thumbnail_url = thumbnail.or_else(|| page.image.map(|i| i.url.into()));
225
226       let (embed_title, embed_description, embed_video_url) = metadata_res
227         .map(|u| (u.title, u.description, u.embed_video_url))
228         .unwrap_or_default();
229       let slur_regex = &local_site_opt_to_slur_regex(&local_site);
230
231       let body_slurs_removed =
232         read_from_string_or_source_opt(&page.content, &page.media_type, &page.source)
233           .map(|s| remove_slurs(&s, slur_regex));
234       let language_id =
235         LanguageTag::to_language_id_single(page.language, &mut context.pool()).await?;
236
237       let name = sanitize_html(&name);
238       let embed_title = sanitize_html_opt(&embed_title);
239       let embed_description = sanitize_html_opt(&embed_description);
240
241       PostInsertForm {
242         name,
243         url: url.map(Into::into),
244         body: body_slurs_removed,
245         creator_id: creator.id,
246         community_id: community.id,
247         removed: None,
248         locked: page.comments_enabled.map(|e| !e),
249         published: page.published.map(|u| u.naive_local()),
250         updated: page.updated.map(|u| u.naive_local()),
251         deleted: Some(false),
252         nsfw: page.sensitive,
253         embed_title,
254         embed_description,
255         embed_video_url,
256         thumbnail_url,
257         ap_id: Some(page.id.clone().into()),
258         local: Some(false),
259         language_id,
260         featured_community: None,
261         featured_local: None,
262       }
263     } else {
264       // if is mod action, only update locked/stickied fields, nothing else
265       PostInsertForm::builder()
266         .name(name)
267         .creator_id(creator.id)
268         .community_id(community.id)
269         .ap_id(Some(page.id.clone().into()))
270         .locked(page.comments_enabled.map(|e| !e))
271         .updated(page.updated.map(|u| u.naive_local()))
272         .build()
273     };
274
275     let post = Post::create(&mut context.pool(), &form).await?;
276
277     // write mod log entry for lock
278     if Page::is_locked_changed(&old_post, &page.comments_enabled) {
279       let form = ModLockPostForm {
280         mod_person_id: creator.id,
281         post_id: post.id,
282         locked: Some(post.locked),
283       };
284       ModLockPost::create(&mut context.pool(), &form).await?;
285     }
286
287     Ok(post.into())
288   }
289 }
290
291 #[cfg(test)]
292 mod tests {
293   #![allow(clippy::unwrap_used)]
294   #![allow(clippy::indexing_slicing)]
295
296   use super::*;
297   use crate::{
298     objects::{
299       community::tests::parse_lemmy_community,
300       person::tests::parse_lemmy_person,
301       post::ApubPost,
302       tests::init_context,
303     },
304     protocol::tests::file_to_json_object,
305   };
306   use lemmy_db_schema::source::site::Site;
307   use serial_test::serial;
308
309   #[tokio::test]
310   #[serial]
311   async fn test_parse_lemmy_post() {
312     let context = init_context().await;
313     let (person, site) = parse_lemmy_person(&context).await;
314     let community = parse_lemmy_community(&context).await;
315
316     let json = file_to_json_object("assets/lemmy/objects/page.json").unwrap();
317     let url = Url::parse("https://enterprise.lemmy.ml/post/55143").unwrap();
318     ApubPost::verify(&json, &url, &context).await.unwrap();
319     let post = ApubPost::from_json(json, &context).await.unwrap();
320
321     assert_eq!(post.ap_id, url.into());
322     assert_eq!(post.name, "Post title");
323     assert!(post.body.is_some());
324     assert_eq!(post.body.as_ref().unwrap().len(), 45);
325     assert!(!post.locked);
326     assert!(!post.featured_community);
327     assert_eq!(context.request_count(), 0);
328
329     Post::delete(&mut context.pool(), post.id).await.unwrap();
330     Person::delete(&mut context.pool(), person.id)
331       .await
332       .unwrap();
333     Community::delete(&mut context.pool(), community.id)
334       .await
335       .unwrap();
336     Site::delete(&mut context.pool(), site.id).await.unwrap();
337   }
338 }