use crate::error::{ApiError, ApiResult}; const USERNAME_MAX_LEN: usize = 30; const FILE_NAME_MAX_LEN: usize = 100; pub fn validate_raw(content: &str) -> ApiResult<()> { for line in content.lines() { if let Some(value) = quoted_value(line, "username") { check_registry_value(value, USERNAME_MAX_LEN)?; } if let Some(value) = quoted_value(line, "file") { check_registry_value(value, FILE_NAME_MAX_LEN)?; } if let Some(names) = array_values(line, "include") { for name in names { check_snippet_name(&name)?; } } } Ok(()) } fn check_registry_value(value: &str, max_len: usize) -> ApiResult<()> { if value.is_empty() { return Err(ApiError::BadRequest("value must not be empty".to_string())); } if value.len() > max_len { return Err(ApiError::BadRequest(format!( "value must be at most {max_len} characters" ))); } if value.contains(':') { return Err(ApiError::BadRequest( "value must not contain ':'".to_string(), )); } Ok(()) } fn check_snippet_name(name: &str) -> ApiResult<()> { if name.is_empty() { return Err(ApiError::BadRequest( "include name must not be empty".to_string(), )); } if name.len() > POLICY_NAME_MAX_LEN { return Err(ApiError::BadRequest(format!( "include name must be at most {POLICY_NAME_MAX_LEN} characters" ))); } if name.contains('/') || name.contains("..") { return Err(ApiError::BadRequest( "include name must not contain path separators".to_string(), )); } Ok(()) } const POLICY_NAME_MAX_LEN: usize = 100; fn quoted_value<'a>(line: &'a str, key: &str) -> Option<&'a str> { let rest = line.trim().strip_prefix(key)?.trim_start(); let rest = rest.strip_prefix('=')?.trim_start(); let rest = rest.strip_prefix('"')?; rest.strip_suffix('"') } fn array_values(line: &str, key: &str) -> Option> { let rest = line.trim().strip_prefix(key)?.trim_start(); let rest = rest.strip_prefix('=')?.trim_start(); let rest = rest.strip_prefix('[')?.trim_start(); let rest = rest.strip_suffix(']')?.trim(); Some( rest.split('"') .enumerate() .filter(|(index, _)| index % 2 == 1) .map(|(_, value)| value.to_string()) .collect(), ) }