1 use crate::error::{LemmyError, LemmyResult};
2 use itertools::Itertools;
3 use once_cell::sync::Lazy;
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,}.*").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")
20 const BODY_MAX_LENGTH: usize = 10000;
21 const POST_BODY_MAX_LENGTH: usize = 50000;
22 const BIO_MAX_LENGTH: usize = 300;
24 fn has_newline(name: &str) -> bool {
28 pub fn is_valid_actor_name(name: &str, actor_name_max_length: usize) -> LemmyResult<()> {
29 let check = name.chars().count() <= actor_name_max_length
30 && VALID_ACTOR_NAME_REGEX.is_match(name)
31 && !has_newline(name);
33 Err(LemmyError::from_message("invalid_name"))
39 // Can't do a regex here, reverse lookarounds not supported
40 pub fn is_valid_display_name(name: &str, actor_name_max_length: usize) -> LemmyResult<()> {
41 let check = !name.starts_with('@')
42 && !name.starts_with('\u{200b}')
43 && name.chars().count() >= 3
44 && name.chars().count() <= actor_name_max_length
45 && !has_newline(name);
47 Err(LemmyError::from_message("invalid_username"))
53 pub fn is_valid_matrix_id(matrix_id: &str) -> LemmyResult<()> {
54 let check = VALID_MATRIX_ID_REGEX.is_match(matrix_id) && !has_newline(matrix_id);
56 Err(LemmyError::from_message("invalid_matrix_id"))
62 pub fn is_valid_post_title(title: &str) -> LemmyResult<()> {
63 let check = VALID_POST_TITLE_REGEX.is_match(title) && !has_newline(title);
65 Err(LemmyError::from_message("invalid_post_title"))
71 /// This could be post bodies, comments, or any description field
72 pub fn is_valid_body_field(body: &Option<String>, post: bool) -> LemmyResult<()> {
73 if let Some(body) = body {
75 body.chars().count() <= POST_BODY_MAX_LENGTH
77 body.chars().count() <= BODY_MAX_LENGTH
81 Err(LemmyError::from_message("invalid_body_field"))
90 pub fn is_valid_bio_field(bio: &str) -> LemmyResult<()> {
91 let check = bio.chars().count() <= BIO_MAX_LENGTH;
93 Err(LemmyError::from_message("bio_length_overflow"))
99 pub fn clean_url_params(url: &Url) -> Url {
100 let mut url_out = url.clone();
101 if url.query().is_some() {
104 .filter(|q| !CLEAN_URL_PARAMS_REGEX.is_match(&q.0))
105 .map(|q| format!("{}={}", q.0, q.1))
107 url_out.set_query(Some(&new_query));
112 pub fn check_totp_2fa_valid(
113 totp_secret: &Option<String>,
114 totp_token: &Option<String>,
117 ) -> LemmyResult<()> {
118 // Check only if they have a totp_secret in the DB
119 if let Some(totp_secret) = totp_secret {
120 // Throw an error if their token is missing
121 let token = totp_token
123 .ok_or_else(|| LemmyError::from_message("missing_totp_token"))?;
125 let totp = build_totp_2fa(site_name, username, totp_secret)?;
127 let check_passed = totp.check_current(token)?;
129 return Err(LemmyError::from_message("incorrect_totp token"));
136 pub fn generate_totp_2fa_secret() -> String {
137 Secret::generate_secret().to_string()
140 pub fn build_totp_2fa(site_name: &str, username: &str, secret: &str) -> Result<TOTP, LemmyError> {
141 let sec = Secret::Raw(secret.as_bytes().to_vec());
144 .map_err(|_| LemmyError::from_message("Couldnt parse totp secret"))?;
147 totp_rs::Algorithm::SHA256,
152 Some(site_name.to_string()),
153 username.to_string(),
155 .map_err(|e| LemmyError::from_error_message(e, "Couldnt generate TOTP"))
158 pub fn check_site_visibility_valid(
159 current_private_instance: bool,
160 current_federation_enabled: bool,
161 new_private_instance: &Option<bool>,
162 new_federation_enabled: &Option<bool>,
163 ) -> LemmyResult<()> {
164 let private_instance = new_private_instance.unwrap_or(current_private_instance);
165 let federation_enabled = new_federation_enabled.unwrap_or(current_federation_enabled);
167 if private_instance && federation_enabled {
168 return Err(LemmyError::from_message(
169 "cant_enable_private_instance_and_federation_together",
178 use super::build_totp_2fa;
179 use crate::utils::validation::{
180 check_site_visibility_valid,
182 generate_totp_2fa_secret,
184 is_valid_display_name,
191 fn test_clean_url_params() {
192 let url = Url::parse("https://example.com/path/123?utm_content=buffercf3b2&utm_medium=social&username=randomuser&id=123").unwrap();
193 let cleaned = clean_url_params(&url);
194 let expected = Url::parse("https://example.com/path/123?username=randomuser&id=123").unwrap();
195 assert_eq!(expected.to_string(), cleaned.to_string());
197 let url = Url::parse("https://example.com/path/123").unwrap();
198 let cleaned = clean_url_params(&url);
199 assert_eq!(url.to_string(), cleaned.to_string());
204 assert!(is_valid_post_title("hi").is_err());
205 assert!(is_valid_post_title("him").is_ok());
206 assert!(is_valid_post_title("n\n\n\n\nanother").is_err());
207 assert!(is_valid_post_title("hello there!\n this is a test.").is_err());
208 assert!(is_valid_post_title("hello there! this is a test.").is_ok());
212 fn test_valid_actor_name() {
213 let actor_name_max_length = 20;
214 assert!(is_valid_actor_name("Hello_98", actor_name_max_length).is_ok());
215 assert!(is_valid_actor_name("ten", actor_name_max_length).is_ok());
216 assert!(is_valid_actor_name("Hello-98", actor_name_max_length).is_err());
217 assert!(is_valid_actor_name("a", actor_name_max_length).is_err());
218 assert!(is_valid_actor_name("", actor_name_max_length).is_err());
222 fn test_valid_display_name() {
223 let actor_name_max_length = 20;
224 assert!(is_valid_display_name("hello @there", actor_name_max_length).is_ok());
225 assert!(is_valid_display_name("@hello there", actor_name_max_length).is_err());
227 // Make sure zero-space with an @ doesn't work
229 is_valid_display_name(&format!("{}@my name is", '\u{200b}'), actor_name_max_length).is_err()
234 fn test_valid_post_title() {
235 assert!(is_valid_post_title("Post Title").is_ok());
236 assert!(is_valid_post_title(" POST TITLE 😃😃😃😃😃").is_ok());
237 assert!(is_valid_post_title("\n \n \n \n ").is_err()); // tabs/spaces/newlines
241 fn test_valid_matrix_id() {
242 assert!(is_valid_matrix_id("@dess:matrix.org").is_ok());
243 assert!(is_valid_matrix_id("dess:matrix.org").is_err());
244 assert!(is_valid_matrix_id(" @dess:matrix.org").is_err());
245 assert!(is_valid_matrix_id("@dess:matrix.org t").is_err());
249 fn test_build_totp() {
250 let generated_secret = generate_totp_2fa_secret();
251 let totp = build_totp_2fa("lemmy", "my_name", &generated_secret);
252 assert!(totp.is_ok());
256 fn test_check_site_visibility_valid() {
257 assert!(check_site_visibility_valid(true, true, &None, &None).is_err());
258 assert!(check_site_visibility_valid(true, false, &None, &Some(true)).is_err());
259 assert!(check_site_visibility_valid(false, true, &Some(true), &None).is_err());
260 assert!(check_site_visibility_valid(false, false, &Some(true), &Some(true)).is_err());
261 assert!(check_site_visibility_valid(true, false, &None, &None).is_ok());
262 assert!(check_site_visibility_valid(false, true, &None, &None).is_ok());
263 assert!(check_site_visibility_valid(false, false, &Some(true), &None).is_ok());
264 assert!(check_site_visibility_valid(false, false, &None, &Some(true)).is_ok());