1 use crate::error::{LemmyError, LemmyErrorExt, LemmyErrorType, LemmyResult};
2 use itertools::Itertools;
3 use once_cell::sync::Lazy;
4 use regex::{Regex, RegexBuilder};
5 use totp_rs::{Secret, TOTP};
8 static VALID_ACTOR_NAME_REGEX: Lazy<Regex> =
9 Lazy::new(|| Regex::new(r"^[a-zA-Z0-9_]{3,}$").expect("compile regex"));
10 static VALID_POST_TITLE_REGEX: Lazy<Regex> =
11 Lazy::new(|| Regex::new(r".*\S{3,200}.*").expect("compile regex"));
12 static VALID_MATRIX_ID_REGEX: Lazy<Regex> = Lazy::new(|| {
13 Regex::new(r"^@[A-Za-z0-9._=-]+:[A-Za-z0-9.-]+\.[A-Za-z]{2,}$").expect("compile regex")
15 // taken from https://en.wikipedia.org/wiki/UTM_parameters
16 static CLEAN_URL_PARAMS_REGEX: Lazy<Regex> = Lazy::new(|| {
17 Regex::new(r"^utm_source|utm_medium|utm_campaign|utm_term|utm_content|gclid|gclsrc|dclid|fbclid$")
18 .expect("compile regex")
21 const BODY_MAX_LENGTH: usize = 10000;
22 const POST_BODY_MAX_LENGTH: usize = 50000;
23 const BIO_MAX_LENGTH: usize = 300;
24 const SITE_NAME_MAX_LENGTH: usize = 20;
25 const SITE_NAME_MIN_LENGTH: usize = 1;
26 const SITE_DESCRIPTION_MAX_LENGTH: usize = 150;
27 //Invisible unicode characters, taken from https://invisible-characters.com/
28 const FORBIDDEN_DISPLAY_CHARS: [char; 53] = [
84 fn has_newline(name: &str) -> bool {
88 pub fn is_valid_actor_name(name: &str, actor_name_max_length: usize) -> LemmyResult<()> {
89 let check = name.chars().count() <= actor_name_max_length
90 && VALID_ACTOR_NAME_REGEX.is_match(name)
91 && !has_newline(name);
93 Err(LemmyErrorType::InvalidName.into())
99 // Can't do a regex here, reverse lookarounds not supported
100 pub fn is_valid_display_name(name: &str, actor_name_max_length: usize) -> LemmyResult<()> {
101 let check = !name.contains(FORBIDDEN_DISPLAY_CHARS)
102 && !name.starts_with('@')
103 && name.chars().count() >= 3
104 && name.chars().count() <= actor_name_max_length
105 && !has_newline(name);
107 Err(LemmyErrorType::InvalidDisplayName.into())
113 pub fn is_valid_matrix_id(matrix_id: &str) -> LemmyResult<()> {
114 let check = VALID_MATRIX_ID_REGEX.is_match(matrix_id) && !has_newline(matrix_id);
116 Err(LemmyErrorType::InvalidMatrixId.into())
122 pub fn is_valid_post_title(title: &str) -> LemmyResult<()> {
123 let check = VALID_POST_TITLE_REGEX.is_match(title) && !has_newline(title);
125 Err(LemmyErrorType::InvalidPostTitle.into())
131 /// This could be post bodies, comments, or any description field
132 pub fn is_valid_body_field(body: &Option<String>, post: bool) -> LemmyResult<()> {
133 if let Some(body) = body {
134 let check = if post {
135 body.chars().count() <= POST_BODY_MAX_LENGTH
137 body.chars().count() <= BODY_MAX_LENGTH
141 Err(LemmyErrorType::InvalidBodyField.into())
150 pub fn is_valid_bio_field(bio: &str) -> LemmyResult<()> {
151 max_length_check(bio, BIO_MAX_LENGTH, LemmyErrorType::BioLengthOverflow)
154 /// Checks the site name length, the limit as defined in the DB.
155 pub fn site_name_length_check(name: &str) -> LemmyResult<()> {
156 min_max_length_check(
158 SITE_NAME_MIN_LENGTH,
159 SITE_NAME_MAX_LENGTH,
160 LemmyErrorType::SiteNameRequired,
161 LemmyErrorType::SiteNameLengthOverflow,
165 /// Checks the site description length, the limit as defined in the DB.
166 pub fn site_description_length_check(description: &str) -> LemmyResult<()> {
169 SITE_DESCRIPTION_MAX_LENGTH,
170 LemmyErrorType::SiteDescriptionLengthOverflow,
174 fn max_length_check(item: &str, max_length: usize, error_type: LemmyErrorType) -> LemmyResult<()> {
175 if item.len() > max_length {
176 Err(error_type.into())
182 fn min_max_length_check(
186 min_msg: LemmyErrorType,
187 max_msg: LemmyErrorType,
188 ) -> LemmyResult<()> {
189 if item.len() > max_length {
191 } else if item.len() < min_length {
198 /// Attempts to build a regex and check it for common errors before inserting into the DB.
199 pub fn build_and_check_regex(regex_str_opt: &Option<&str>) -> LemmyResult<Option<Regex>> {
200 regex_str_opt.map_or_else(
201 || Ok(None::<Regex>),
203 if regex_str.is_empty() {
204 // If the proposed regex is empty, return as having no regex at all; this is the same
205 // behavior that happens downstream before the write to the database.
206 return Ok(None::<Regex>);
209 RegexBuilder::new(regex_str)
210 .case_insensitive(true)
212 .with_lemmy_type(LemmyErrorType::InvalidRegex)
214 // NOTE: It is difficult to know, in the universe of user-crafted regex, which ones
215 // may match against any string text. To keep it simple, we'll match the regex
216 // against an innocuous string - a single number - which should help catch a regex
217 // that accidentally matches against all strings.
218 if regex.is_match("1") {
219 return Err(LemmyErrorType::PermissiveRegex.into());
228 pub fn clean_url_params(url: &Url) -> Url {
229 let mut url_out = url.clone();
230 if url.query().is_some() {
233 .filter(|q| !CLEAN_URL_PARAMS_REGEX.is_match(&q.0))
234 .map(|q| format!("{}={}", q.0, q.1))
236 url_out.set_query(Some(&new_query));
241 pub fn check_totp_2fa_valid(
242 totp_secret: &Option<String>,
243 totp_token: &Option<String>,
246 ) -> LemmyResult<()> {
247 // Check only if they have a totp_secret in the DB
248 if let Some(totp_secret) = totp_secret {
249 // Throw an error if their token is missing
250 let token = totp_token
252 .ok_or(LemmyErrorType::MissingTotpToken)?;
254 let totp = build_totp_2fa(site_name, username, totp_secret)?;
256 let check_passed = totp.check_current(token)?;
258 return Err(LemmyErrorType::IncorrectTotpToken.into());
265 pub fn generate_totp_2fa_secret() -> String {
266 Secret::generate_secret().to_string()
269 pub fn build_totp_2fa(site_name: &str, username: &str, secret: &str) -> Result<TOTP, LemmyError> {
270 let sec = Secret::Raw(secret.as_bytes().to_vec());
273 .map_err(|_| LemmyErrorType::CouldntParseTotpSecret)?;
276 totp_rs::Algorithm::SHA256,
281 Some(site_name.to_string()),
282 username.to_string(),
284 .with_lemmy_type(LemmyErrorType::CouldntGenerateTotp)
287 pub fn check_site_visibility_valid(
288 current_private_instance: bool,
289 current_federation_enabled: bool,
290 new_private_instance: &Option<bool>,
291 new_federation_enabled: &Option<bool>,
292 ) -> LemmyResult<()> {
293 let private_instance = new_private_instance.unwrap_or(current_private_instance);
294 let federation_enabled = new_federation_enabled.unwrap_or(current_federation_enabled);
296 if private_instance && federation_enabled {
297 return Err(LemmyErrorType::CantEnablePrivateInstanceAndFederationTogether.into());
303 pub fn check_url_scheme(url: &Option<Url>) -> LemmyResult<()> {
304 if let Some(url) = url {
305 if url.scheme() != "http" && url.scheme() != "https" {
306 return Err(LemmyErrorType::InvalidUrlScheme.into());
314 use super::build_totp_2fa;
316 error::LemmyErrorType,
318 build_and_check_regex,
319 check_site_visibility_valid,
322 generate_totp_2fa_secret,
325 is_valid_display_name,
328 site_description_length_check,
329 site_name_length_check,
331 SITE_DESCRIPTION_MAX_LENGTH,
332 SITE_NAME_MAX_LENGTH,
338 fn test_clean_url_params() {
339 let url = Url::parse("https://example.com/path/123?utm_content=buffercf3b2&utm_medium=social&username=randomuser&id=123").unwrap();
340 let cleaned = clean_url_params(&url);
341 let expected = Url::parse("https://example.com/path/123?username=randomuser&id=123").unwrap();
342 assert_eq!(expected.to_string(), cleaned.to_string());
344 let url = Url::parse("https://example.com/path/123").unwrap();
345 let cleaned = clean_url_params(&url);
346 assert_eq!(url.to_string(), cleaned.to_string());
351 assert!(is_valid_post_title("hi").is_err());
352 assert!(is_valid_post_title("him").is_ok());
353 assert!(is_valid_post_title("n\n\n\n\nanother").is_err());
354 assert!(is_valid_post_title("hello there!\n this is a test.").is_err());
355 assert!(is_valid_post_title("hello there! this is a test.").is_ok());
359 fn test_valid_actor_name() {
360 let actor_name_max_length = 20;
361 assert!(is_valid_actor_name("Hello_98", actor_name_max_length).is_ok());
362 assert!(is_valid_actor_name("ten", actor_name_max_length).is_ok());
363 assert!(is_valid_actor_name("Hello-98", actor_name_max_length).is_err());
364 assert!(is_valid_actor_name("a", actor_name_max_length).is_err());
365 assert!(is_valid_actor_name("", actor_name_max_length).is_err());
369 fn test_valid_display_name() {
370 let actor_name_max_length = 20;
371 assert!(is_valid_display_name("hello @there", actor_name_max_length).is_ok());
372 assert!(is_valid_display_name("@hello there", actor_name_max_length).is_err());
374 // Make sure zero-space with an @ doesn't work
376 is_valid_display_name(&format!("{}@my name is", '\u{200b}'), actor_name_max_length).is_err()
381 fn test_valid_post_title() {
382 assert!(is_valid_post_title("Post Title").is_ok());
383 assert!(is_valid_post_title(" POST TITLE 😃😃😃😃😃").is_ok());
384 assert!(is_valid_post_title("\n \n \n \n ").is_err()); // tabs/spaces/newlines
388 fn test_valid_matrix_id() {
389 assert!(is_valid_matrix_id("@dess:matrix.org").is_ok());
390 assert!(is_valid_matrix_id("dess:matrix.org").is_err());
391 assert!(is_valid_matrix_id(" @dess:matrix.org").is_err());
392 assert!(is_valid_matrix_id("@dess:matrix.org t").is_err());
396 fn test_build_totp() {
397 let generated_secret = generate_totp_2fa_secret();
398 let totp = build_totp_2fa("lemmy", "my_name", &generated_secret);
399 assert!(totp.is_ok());
403 fn test_valid_site_name() {
405 (0..SITE_NAME_MAX_LENGTH).map(|_| 'A').collect::<String>(),
408 let invalid_names = [
410 &(0..SITE_NAME_MAX_LENGTH + 1)
412 .collect::<String>(),
413 LemmyErrorType::SiteNameLengthOverflow,
415 (&String::new(), LemmyErrorType::SiteNameRequired),
418 valid_names.iter().for_each(|valid_name| {
420 site_name_length_check(valid_name).is_ok(),
421 "Expected {} of length {} to be Ok.",
429 .for_each(|(invalid_name, expected_err)| {
430 let result = site_name_length_check(invalid_name);
432 assert!(result.is_err());
437 .eq(&Some(expected_err.clone())),
438 "Testing {}, expected error {}",
446 fn test_valid_bio() {
447 assert!(is_valid_bio_field(&(0..BIO_MAX_LENGTH).map(|_| 'A').collect::<String>()).is_ok());
450 is_valid_bio_field(&(0..BIO_MAX_LENGTH + 1).map(|_| 'A').collect::<String>());
453 invalid_result.is_err()
457 .eq(&Some(LemmyErrorType::BioLengthOverflow))
462 fn test_valid_site_description() {
463 assert!(site_description_length_check(
464 &(0..SITE_DESCRIPTION_MAX_LENGTH)
470 let invalid_result = site_description_length_check(
471 &(0..SITE_DESCRIPTION_MAX_LENGTH + 1)
473 .collect::<String>(),
477 invalid_result.is_err()
481 .eq(&Some(LemmyErrorType::SiteDescriptionLengthOverflow))
486 fn test_valid_slur_regex() {
487 let valid_regexes = [&None, &Some(""), &Some("(foo|bar)")];
489 valid_regexes.iter().for_each(|regex| {
490 let result = build_and_check_regex(regex);
492 assert!(result.is_ok(), "Testing regex: {:?}", regex);
497 fn test_too_permissive_slur_regex() {
498 let match_everything_regexes = [
499 (&Some("["), LemmyErrorType::InvalidRegex),
500 (&Some("(foo|bar|)"), LemmyErrorType::PermissiveRegex),
501 (&Some(".*"), LemmyErrorType::PermissiveRegex),
504 match_everything_regexes
506 .for_each(|(regex_str, expected_err)| {
507 let result = build_and_check_regex(regex_str);
509 assert!(result.is_err());
514 .eq(&Some(expected_err.clone())),
515 "Testing regex {:?}, expected error {}",
523 fn test_check_site_visibility_valid() {
524 assert!(check_site_visibility_valid(true, true, &None, &None).is_err());
525 assert!(check_site_visibility_valid(true, false, &None, &Some(true)).is_err());
526 assert!(check_site_visibility_valid(false, true, &Some(true), &None).is_err());
527 assert!(check_site_visibility_valid(false, false, &Some(true), &Some(true)).is_err());
528 assert!(check_site_visibility_valid(true, false, &None, &None).is_ok());
529 assert!(check_site_visibility_valid(false, true, &None, &None).is_ok());
530 assert!(check_site_visibility_valid(false, false, &Some(true), &None).is_ok());
531 assert!(check_site_visibility_valid(false, false, &None, &Some(true)).is_ok());
535 fn test_check_url_scheme() {
536 assert!(check_url_scheme(&None).is_ok());
537 assert!(check_url_scheme(&Some(Url::parse("http://example.com").unwrap())).is_ok());
538 assert!(check_url_scheme(&Some(Url::parse("https://example.com").unwrap())).is_ok());
539 assert!(check_url_scheme(&Some(Url::parse("ftp://example.com").unwrap())).is_err());
540 assert!(check_url_scheme(&Some(Url::parse("javascript:void").unwrap())).is_err());