Skip to content

Open source, composable payments platform | PCI compliant | SaaS and Self-host options | Enables connectivity to multiple payment, payout, fraud, vault and tokenization providers | Uplifts authorization with intelligent routing and revenue recovery | Reduce payment processing costs with cost observability | Reduces payment ops with reconciliation

fix(themes): use safeString for themedata and email types (#14994)

Muditbhatia12f5a7e339ec92
diff --git a/crates/api_models/src/user/theme.rs b/crates/api_models/src/user/theme.rs
index 16f6a8d6f9..14c3728c1d 100644
--- a/crates/api_models/src/user/theme.rs
+++ b/crates/api_models/src/user/theme.rs
@@ -1,8 +1,9 @@
use actix_multipart::form::{bytes::Bytes, text::Text, MultipartForm};
use common_enums::EntityType;
+use common_types::{primitive_wrappers::SafeString, user::theme::EmailThemeConfig};
use common_utils::{
id_type,
- types::user::{EmailThemeConfig, ThemeLineage},
+ types::{user::ThemeLineage, Url},
};
use hyperswitch_masking::Secret;
use serde::{Deserialize, Serialize};
@@ -10,7 +11,7 @@ use serde::{Deserialize, Serialize};
#[derive(Debug, Serialize)]
pub struct GetThemeResponse {
pub theme_id: String,
- pub theme_name: String,
+ pub theme_name: SafeString,
pub entity_type: EntityType,
pub tenant_id: id_type::TenantId,
pub org_id: Option<id_type::OrganizationId>,
@@ -28,21 +29,21 @@ pub struct ThemeVersionResponse {
#[derive(Debug, MultipartForm)]
pub struct UploadFileAssetData {
- pub asset_name: Text<String>,
+ pub asset_name: Text<SafeString>,
#[multipart(limit = "10MB")]
pub asset_data: Bytes,
}
#[derive(Serialize, Deserialize, Debug)]
pub struct UploadFileRequest {
- pub asset_name: String,
+ pub asset_name: SafeString,
pub asset_data: Secret<Vec<u8>>,
}
#[derive(Serialize, Deserialize, Debug)]
pub struct CreateThemeRequest {
pub lineage: ThemeLineage,
- pub theme_name: String,
+ pub theme_name: SafeString,
pub theme_data: ThemeData,
pub email_config: Option<EmailThemeConfig>,
}
@@ -50,7 +51,7 @@ pub struct CreateThemeRequest {
#[derive(Serialize, Deserialize, Debug)]
pub struct CreateUserThemeRequest {
pub entity_type: EntityType,
- pub theme_name: String,
+ pub theme_name: SafeString,
pub theme_data: ThemeData,
pub email_config: Option<EmailThemeConfig>,
}
@@ -84,28 +85,28 @@ struct Settings {
#[derive(Serialize, Deserialize, Debug)]
#[serde(rename_all = "camelCase")]
struct Colors {
- primary: String,
- secondary: Option<String>,
- background: Option<String>,
+ primary: SafeString,
+ secondary: Option<SafeString>,
+ background: Option<SafeString>,
}
#[derive(Serialize, Deserialize, Debug)]
#[serde(rename_all = "camelCase")]
struct Sidebar {
- primary: String,
- text_color: Option<String>,
- text_color_primary: Option<String>,
+ primary: SafeString,
+ text_color: Option<SafeString>,
+ text_color_primary: Option<SafeString>,
}
#[derive(Serialize, Deserialize, Debug)]
#[serde(rename_all = "camelCase")]
struct Typography {
- font_family: Option<String>,
- font_size: Option<String>,
- heading_font_size: Option<String>,
- text_color: Option<String>,
- link_color: Option<String>,
- link_hover_color: Option<String>,
+ font_family: Option<SafeString>,
+ font_size: Option<SafeString>,
+ heading_font_size: Option<SafeString>,
+ text_color: Option<SafeString>,
+ link_color: Option<SafeString>,
+ link_hover_color: Option<SafeString>,
}
#[derive(Serialize, Deserialize, Debug)]
@@ -118,38 +119,38 @@ struct Buttons {
#[derive(Serialize, Deserialize, Debug)]
#[serde(rename_all = "camelCase")]
struct PrimaryButton {
- background_color: Option<String>,
- text_color: Option<String>,
- hover_background_color: String,
+ background_color: Option<SafeString>,
+ text_color: Option<SafeString>,
+ hover_background_color: SafeString,
}
#[derive(Serialize, Deserialize, Debug)]
#[serde(rename_all = "camelCase")]
struct SecondaryButton {
- background_color: Option<String>,
- text_color: Option<String>,
- hover_background_color: Option<String>,
+ background_color: Option<SafeString>,
+ text_color: Option<SafeString>,
+ hover_background_color: Option<SafeString>,
}
#[derive(Serialize, Deserialize, Debug)]
#[serde(rename_all = "camelCase")]
struct Borders {
- default_radius: Option<String>,
- border_color: Option<String>,
+ default_radius: Option<SafeString>,
+ border_color: Option<SafeString>,
}
#[derive(Serialize, Deserialize, Debug)]
#[serde(rename_all = "camelCase")]
struct Spacing {
- padding: Option<String>,
- margin: Option<String>,
+ padding: Option<SafeString>,
+ margin: Option<SafeString>,
}
#[derive(Serialize, Deserialize, Debug)]
#[serde(rename_all = "camelCase")]
struct Urls {
- favicon_url: Option<String>,
- logo_url: Option<String>,
+ favicon_url: Option<Url>,
+ logo_url: Option<Url>,
}
#[derive(Serialize, Deserialize, Debug)]
diff --git a/crates/common_types/src/lib.rs b/crates/common_types/src/lib.rs
index 2f0fa8e009..f013ed8d9f 100644
--- a/crates/common_types/src/lib.rs
+++ b/crates/common_types/src/lib.rs
@@ -14,6 +14,7 @@ pub mod primitive_wrappers;
pub mod refunds;
/// types for three ds decision rule engine
pub mod three_ds_decision_rule_engine;
+pub mod user;
///types for callback mapper
pub mod callback_mapper;
diff --git a/crates/common_types/src/primitive_wrappers.rs b/crates/common_types/src/primitive_wrappers.rs
index 40f00bfedb..d924b4ba32 100644
--- a/crates/common_types/src/primitive_wrappers.rs
+++ b/crates/common_types/src/primitive_wrappers.rs
@@ -581,6 +581,11 @@ mod safe_string {
/// String wrapper that prevents XSS and SQLi attacks
#[derive(Clone, Debug, Eq, PartialEq, Default)]
+ #[cfg_attr(
+ feature = "diesel",
+ derive(diesel::expression::AsExpression, diesel::deserialize::FromSqlRow)
+ )]
+ #[cfg_attr(feature = "diesel", diesel(sql_type = diesel::sql_types::Text))]
pub struct SafeString(String);
impl SafeString {
diff --git a/crates/common_types/src/user.rs b/crates/common_types/src/user.rs
new file mode 100644
index 0000000000..775ff90c3e
--- /dev/null
+++ b/crates/common_types/src/user.rs
@@ -0,0 +1,3 @@
+//! Types related to users
+
+pub mod theme;
diff --git a/crates/common_types/src/user/theme.rs b/crates/common_types/src/user/theme.rs
new file mode 100644
index 0000000000..b5c8444241
--- /dev/null
+++ b/crates/common_types/src/user/theme.rs
@@ -0,0 +1,25 @@
+//! Types related to themes
+
+use common_utils::types::Url;
+use serde::{Deserialize, Serialize};
+
+use crate::primitive_wrappers::SafeString;
+
+/// Struct for holding the theme settings for email
+#[derive(Debug, Clone, Deserialize, Serialize)]
+pub struct EmailThemeConfig {
+ /// The entity name to be used in the email
+ pub entity_name: SafeString,
+
+ /// The URL of the entity logo to be used in the email
+ pub entity_logo_url: Url,
+
+ /// The primary color to be used in the email
+ pub primary_color: SafeString,
+
+ /// The foreground color to be used in the email
+ pub foreground_color: SafeString,
+
+ /// The background color to be used in the email
+ pub background_color: SafeString,
+}
diff --git a/crates/common_utils/src/types.rs b/crates/common_utils/src/types.rs
index b34acc9305..884c32f1f9 100644
--- a/crates/common_utils/src/types.rs
+++ b/crates/common_utils/src/types.rs
@@ -748,7 +748,7 @@ impl StringMajorUnit {
#[derive(
Debug, serde::Deserialize, serde::Serialize, Clone, PartialEq, Eq, Hash, ToSchema, PartialOrd,
)]
-#[cfg_attr(feature = "diesel", derive(AsExpression))]
+#[cfg_attr(feature = "diesel", derive(FromSqlRow, AsExpression))]
#[cfg_attr(feature = "diesel", diesel(sql_type = sql_types::Text))]
/// This domain type can be used for any url
pub struct Url(url::Url);
diff --git a/crates/common_utils/src/types/user/theme.rs b/crates/common_utils/src/types/user/theme.rs
index b215708949..c052b56f74 100644
--- a/crates/common_utils/src/types/user/theme.rs
+++ b/crates/common_utils/src/types/user/theme.rs
@@ -166,22 +166,3 @@ impl ThemeLineage {
}
}
}
-
-/// Struct for holding the theme settings for email
-#[derive(Debug, Clone, Default, Deserialize, Serialize)]
-pub struct EmailThemeConfig {
- /// The entity name to be used in the email
- pub entity_name: String,
-
- /// The URL of the entity logo to be used in the email
- pub entity_logo_url: String,
-
- /// The primary color to be used in the email
- pub primary_color: String,
-
- /// The foreground color to be used in the email
- pub foreground_color: String,
-
- /// The background color to be used in the email
- pub background_color: String,
-}
diff --git a/crates/diesel_models/src/user/theme.rs b/crates/diesel_models/src/user/theme.rs
index d3ee3f5c8b..2f3eccd6d4 100644
--- a/crates/diesel_models/src/user/theme.rs
+++ b/crates/diesel_models/src/user/theme.rs
@@ -1,7 +1,8 @@
use common_enums::EntityType;
+use common_types::{primitive_wrappers::SafeString, user::theme::EmailThemeConfig};
use common_utils::{
date_time, id_type,
- types::user::{EmailThemeConfig, ThemeLineage},
+ types::{user::ThemeLineage, Url},
};
use diesel::{AsChangeset, Identifiable, Insertable, Queryable, Selectable};
use router_derive::DebugAsDisplay;
@@ -21,12 +22,12 @@ pub struct Theme {
pub created_at: PrimitiveDateTime,
pub last_modified_at: PrimitiveDateTime,
pub entity_type: EntityType,
- pub theme_name: String,
- pub email_primary_color: String,
- pub email_foreground_color: String,
- pub email_background_color: String,
- pub email_entity_name: String,
- pub email_entity_logo_url: String,
+ pub theme_name: SafeString,
+ pub email_primary_color: SafeString,
+ pub email_foreground_color: SafeString,
+ pub email_background_color: SafeString,
+ pub email_entity_name: SafeString,
+ pub email_entity_logo_url: Url,
pub theme_config_version: String,
}
@@ -41,19 +42,19 @@ pub struct ThemeNew {
pub created_at: PrimitiveDateTime,
pub last_modified_at: PrimitiveDateTime,
pub entity_type: EntityType,
- pub theme_name: String,
- pub email_primary_color: String,
- pub email_foreground_color: String,
- pub email_background_color: String,
- pub email_entity_name: String,
- pub email_entity_logo_url: String,
+ pub theme_name: SafeString,
+ pub email_primary_color: SafeString,
+ pub email_foreground_color: SafeString,
+ pub email_background_color: SafeString,
+ pub email_entity_name: SafeString,
+ pub email_entity_logo_url: Url,
pub theme_config_version: String,
}
impl ThemeNew {
pub fn new(
theme_id: String,
- theme_name: String,
+ theme_name: SafeString,
lineage: ThemeLineage,
email_config: EmailThemeConfig,
) -> Self {
@@ -94,11 +95,11 @@ impl Theme {
#[derive(Clone, Debug, AsChangeset, DebugAsDisplay)]
#[diesel(table_name = themes)]
pub struct ThemeUpdateInternal {
- pub email_primary_color: Option<String>,
- pub email_foreground_color: Option<String>,
- pub email_background_color: Option<String>,
- pub email_entity_name: Option<String>,
- pub email_entity_logo_url: Option<String>,
+ pub email_primary_color: Option<SafeString>,
+ pub email_foreground_color: Option<SafeString>,
+ pub email_background_color: Option<SafeString>,
+ pub email_entity_name: Option<SafeString>,
+ pub email_entity_logo_url: Option<Url>,
pub last_modified_at: PrimitiveDateTime,
pub theme_config_version: Option<String>,
}
diff --git a/crates/router/src/configs/settings.rs b/crates/router/src/configs/settings.rs
index dd6f7dfff3..a16890beab 100644
--- a/crates/router/src/configs/settings.rs
+++ b/crates/router/src/configs/settings.rs
@@ -8,7 +8,8 @@ use std::{
use analytics::{opensearch::OpenSearchConfig, ReportConfig};
use api_models::enums;
use common_enums;
-use common_utils::{ext_traits::ConfigExt, id_type, types::user::EmailThemeConfig};
+use common_types::{primitive_wrappers::SafeString, user::theme::EmailThemeConfig};
+use common_utils::{ext_traits::ConfigExt, id_type, types::Url};
use config::{Environment, File};
use error_stack::ResultExt;
#[cfg(feature = "email")]
@@ -1846,12 +1847,31 @@ impl Default for CellInformation {
}
}
-#[derive(Debug, Deserialize, Clone, Default)]
+#[derive(Debug, Deserialize, Clone)]
pub struct ThemeSettings {
pub storage: FileStorageConfig,
pub email_config: EmailThemeConfig,
}
+impl Default for ThemeSettings {
+ fn default() -> Self {
+ Self {
+ storage: FileStorageConfig::default(),
+ email_config: EmailThemeConfig {
+ entity_name: SafeString::default(),
+ #[allow(clippy::expect_used)]
+ entity_logo_url: Url::wrap(
+ url::Url::parse("https://example.com/Logo.png")
+ .expect("Failed to parse default email entity logo URL"),
+ ),
+ primary_color: SafeString::default(),
+ foreground_color: SafeString::default(),
+ background_color: SafeString::default(),
+ },
+ }
+ }
+}
+
fn deserialize_hashmap_inner<K, V>(
value: HashMap<String, String>,
) -> Result<HashMap<K, HashSet<V>>, String>
diff --git a/crates/router/src/core/errors/user.rs b/crates/router/src/core/errors/user.rs
index 54fade8a98..c14ef8fb5e 100644
--- a/crates/router/src/core/errors/user.rs
+++ b/crates/router/src/core/errors/user.rs
@@ -104,6 +104,8 @@ pub enum UserErrors {
ErrorRetrievingFile,
#[error("Theme not found")]
ThemeNotFound,
+ #[error("Invalid theme asset name")]
+ InvalidThemeAssetName,
#[error("Theme with lineage already exists")]
ThemeAlreadyExists,
#[error("Invalid field: {0} in lineage")]
@@ -291,6 +293,9 @@ impl common_utils::errors::ErrorSwitch<api_models::errors::types::ApiErrorRespon
Self::ThemeNotFound => {
AER::NotFound(ApiError::new(sub_code, 53, self.get_error_message(), None))
}
+ Self::InvalidThemeAssetName => {
+ AER::BadRequest(ApiError::new(sub_code, 66, self.get_error_message(), None))
+ }
Self::ThemeAlreadyExists => {
AER::BadRequest(ApiError::new(sub_code, 54, self.get_error_message(), None))
}
@@ -392,6 +397,7 @@ impl UserErrors {
Self::ErrorUploadingFile => "Error Uploading file to Theme Storage".to_string(),
Self::ErrorRetrievingFile => "Error Retrieving file from Theme Storage".to_string(),
Self::ThemeNotFound => "Theme not found".to_string(),
+ Self::InvalidThemeAssetName => "Invalid theme asset name".to_string(),
Self::ThemeAlreadyExists => "Theme with lineage already exists".to_string(),
Self::InvalidThemeLineage(field_name) => {
format!("Invalid field: {field_name} in lineage")
diff --git a/crates/router/src/core/user/theme.rs b/crates/router/src/core/user/theme.rs
index 02c2bf8e56..850fb4e888 100644
--- a/crates/router/src/core/user/theme.rs
+++ b/crates/router/src/core/user/theme.rs
@@ -5,7 +5,7 @@ use common_utils::{
types::user::ThemeLineage,
};
use diesel_models::user::theme::{ThemeNew, ThemeUpdate};
-use error_stack::ResultExt;
+use error_stack::{report, ResultExt};
use hyperswitch_domain_models::api::ApplicationResponse;
use hyperswitch_masking::ExposeInterface;
use rdkafka::message::ToBytes;
@@ -100,6 +100,8 @@ pub async fn upload_file_to_theme_storage(
.await
.to_not_found_response(UserErrors::ThemeNotFound)?;
+ theme_utils::validate_asset_name(&request.asset_name)?;
+
theme_utils::upload_file_to_theme_bucket(
&state,
&theme_utils::get_specific_file_key(&db_theme.theme_id, &request.asset_name),
@@ -257,6 +259,24 @@ pub async fn create_user_theme(
.email_config
.unwrap_or(state.conf.theme.email_config.clone())
};
+
+ let user_entity_type = user_from_token
+ .get_role_info_from_db(&state)
+ .await
+ .attach_printable("Invalid role_id in JWT")?
+ .get_entity_type();
+
+ if request.entity_type > user_entity_type {
+ Err(
+ report!(UserErrors::InvalidThemeLineage("entity_type".to_string())).attach_printable(
+ format!(
+ "User with entity type {user_entity_type} cannot create theme at {} lineage",
+ request.entity_type
+ ),
+ ),
+ )?;
+ }
+
let lineage = theme_utils::get_theme_lineage_from_user_token(
&user_from_token,
&state,
@@ -439,6 +459,7 @@ pub async fn upload_file_to_user_theme_storage(
let user_entity_type = user_role_info.get_entity_type();
theme_utils::can_user_access_theme(&user_from_token, &user_entity_type, &db_theme).await?;
+ theme_utils::validate_asset_name(&request.asset_name)?;
theme_utils::upload_file_to_theme_bucket(
&state,
&theme_utils::get_specific_file_key(&db_theme.theme_id, &request.asset_name),
diff --git a/crates/router/src/services/email/types.rs b/crates/router/src/services/email/types.rs
index 19c41ae89c..2953e0fa2c 100644
--- a/crates/router/src/services/email/types.rs
+++ b/crates/router/src/services/email/types.rs
@@ -1,6 +1,7 @@
use api_models::user::dashboard_metadata::ProdIntent;
use common_enums::{EntityType, MerchantProductType};
-use common_utils::{errors::CustomResult, pii, types::user::EmailThemeConfig};
+use common_types::user::theme::EmailThemeConfig;
+use common_utils::{errors::CustomResult, pii};
use diesel_models::organization::OrganizationBridge;
use error_stack::ResultExt;
use external_services::email::{EmailContents, EmailData, EmailError};
@@ -411,17 +412,21 @@ impl EmailData for VerifyEmail {
let body = html::get_html_body(EmailBody::Verify {
link: verify_email_link,
- entity_name: self.theme_config.entity_name.clone(),
- entity_logo_url: self.theme_config.entity_logo_url.clone(),
- primary_color: self.theme_config.primary_color.clone(),
- background_color: self.theme_config.background_color.clone(),
- foreground_color: self.theme_config.foreground_color.clone(),
+ entity_name: self.theme_config.entity_name.clone().into_inner(),
+ entity_logo_url: self
+ .theme_config
+ .entity_logo_url
+ .get_string_repr()
+ .to_string(),
+ primary_color: self.theme_config.primary_color.clone().into_inner(),
+ background_color: self.theme_config.background_color.clone().into_inner(),
+ foreground_color: self.theme_config.foreground_color.clone().into_inner(),
});
Ok(EmailContents {
subject: format!(
"Welcome to the {} community!",
- self.theme_config.entity_name
+ self.theme_config.entity_name.as_str()
),
body: external_services::email::IntermediateString::new(body),
recipients: self.recipient_email.clone().into_inner().into(),
@@ -461,17 +466,21 @@ impl EmailData for ResetPassword {
let body = html::get_html_body(EmailBody::Reset {
link: reset_password_link,
user_name: self.user_name.clone().get_secret().expose(),
- entity_name: self.theme_config.entity_name.clone(),
- entity_logo_url: self.theme_config.entity_logo_url.clone(),
- primary_color: self.theme_config.primary_color.clone(),
- background_color: self.theme_config.background_color.clone(),
- foreground_color: self.theme_config.foreground_color.clone(),
+ entity_name: self.theme_config.entity_name.clone().into_inner(),
+ entity_logo_url: self
+ .theme_config
+ .entity_logo_url
+ .get_string_repr()
+ .to_string(),
+ primary_color: self.theme_config.primary_color.clone().into_inner(),
+ background_color: self.theme_config.background_color.clone().into_inner(),
+ foreground_color: self.theme_config.foreground_color.clone().into_inner(),
});
Ok(EmailContents {
subject: format!(
"Get back to {} - Reset Your Password Now!",
- self.theme_config.entity_name
+ self.theme_config.entity_name.as_str()
),
body: external_services::email::IntermediateString::new(body),
recipients: self.recipient_email.clone().into_inner().into(),
@@ -511,17 +520,21 @@ impl EmailData for MagicLink {
let body = html::get_html_body(EmailBody::MagicLink {
link: magic_link_login,
user_name: self.user_name.clone().get_secret().expose(),
- entity_name: self.theme_config.entity_name.clone(),
- entity_logo_url: self.theme_config.entity_logo_url.clone(),
- primary_color: self.theme_config.primary_color.clone(),
- background_color: self.theme_config.background_color.clone(),
- foreground_color: self.theme_config.foreground_color.clone(),
+ entity_name: self.theme_config.entity_name.clone().into_inner(),
+ entity_logo_url: self
+ .theme_config
+ .entity_logo_url
+ .get_string_repr()
+ .to_string(),
+ primary_color: self.theme_config.primary_color.clone().into_inner(),
+ background_color: self.theme_config.background_color.clone().into_inner(),
+ foreground_color: self.theme_config.foreground_color.clone().into_inner(),
});
Ok(EmailContents {
subject: format!(
"Unlock {}: Use Your Magic Link to Sign In",
- self.theme_config.entity_name
+ self.theme_config.entity_name.as_str()
),
body: external_services::email::IntermediateString::new(body),
recipients: self.recipient_email.clone().into_inner().into(),
@@ -561,17 +574,21 @@ impl EmailData for InviteUser {
let body = html::get_html_body(EmailBody::AcceptInviteFromEmail {
link: invite_user_link,
user_name: self.user_name.clone().get_secret().expose(),
- entity_name: self.theme_config.entity_name.clone(),
- entity_logo_url: self.theme_config.entity_logo_url.clone(),
- primary_color: self.theme_config.primary_color.clone(),
- background_color: self.theme_config.background_color.clone(),
- foreground_color: self.theme_config.foreground_color.clone(),
+ entity_name: self.theme_config.entity_name.clone().into_inner(),
+ entity_logo_url: self
+ .theme_config
+ .entity_logo_url
+ .get_string_repr()
+ .to_string(),
+ primary_color: self.theme_config.primary_color.clone().into_inner(),
+ background_color: self.theme_config.background_color.clone().into_inner(),
+ foreground_color: self.theme_config.foreground_color.clone().into_inner(),
});
Ok(EmailContents {
subject: format!(
"You have been invited to join {} Community!",
- self.theme_config.entity_name
+ self.theme_config.entity_name.as_str()
),
body: external_services::email::IntermediateString::new(body),
recipients: self.recipient_email.clone().into_inner().into(),
@@ -799,10 +816,14 @@ impl EmailData for RoleDeleted {
role_name: self.role_name.clone(),
entity_type: format!("{:?}", self.entity_type),
lineage_info,
- entity_name: self.theme_config.entity_name.clone(),
- entity_logo_url: self.theme_config.entity_logo_url.clone(),
- background_color: self.theme_config.background_color.clone(),
- foreground_color: self.theme_config.foreground_color.clone(),
+ entity_name: self.theme_config.entity_name.clone().into_inner(),
+ entity_logo_url: self
+ .theme_config
+ .entity_logo_url
+ .get_string_repr()
+ .to_string(),
+ background_color: self.theme_config.background_color.clone().into_inner(),
+ foreground_color: self.theme_config.foreground_color.clone().into_inner(),
});
Ok(EmailContents {
diff --git a/crates/router/src/utils/user/theme.rs b/crates/router/src/utils/user/theme.rs
index 1bd43b0ca5..423300b96d 100644
--- a/crates/router/src/utils/user/theme.rs
+++ b/crates/router/src/utils/user/theme.rs
@@ -1,4 +1,4 @@
-use std::path::PathBuf;
+use std::path::{Component, Path, PathBuf};
use common_enums::EntityType;
use common_utils::{ext_traits::AsyncExt, id_type, types::user::ThemeLineage};
@@ -78,6 +78,24 @@ pub fn get_theme_file_key(theme_id: &str) -> PathBuf {
get_specific_file_key(theme_id, "theme.json")
}
+/// Checks that the asset name is a single plain file name, other than `theme.json`
+pub fn validate_asset_name(asset_name: &str) -> UserResult<()> {
+ let mut components = Path::new(asset_name).components();
+
+ let is_single_normal_component = matches!(
+ (components.next(), components.next()),
+ (Some(Component::Normal(_)), None)
+ );
+ // `Path::components` ignores a trailing `/` and treats `\` as a regular character on Unix
+ let has_separator = asset_name.contains(['/', '\\']);
+
+ if is_single_normal_component && !has_separator && asset_name != "theme.json" {
+ Ok(())
+ } else {
+ Err(UserErrors::InvalidThemeAssetName.into())
+ }
+}
+
fn path_buf_to_str(path: &PathBuf) -> UserResult<&str> {
path.to_str()
.ok_or(UserErrors::InternalServerError)