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
Rust adyenbeginner-friendlyfeaturedfinancefintechhacktoberfesthigh-performanceopen-sourceorchestrationpaymentpayment-gatewaypayment-integrationpayment-processingpaymentspayments-platformrestful-apirustsdkstripeworks-with-react
fix(config): decrypt service credentials at startup (#15034)
Shankar Singh C8ed30295bb3c
diff --git a/Cargo.lock b/Cargo.lockindex 7765e0c8b5..235cd7198e 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -4888,6 +4888,7 @@ dependencies = ["serde","serde_json","strum 0.26.3",+ "subtle","thiserror 1.0.69","time","tokio 1.48.0",diff --git a/config/config.example.toml b/config/config.example.tomlindex e196c2d344..0425103312 100644--- a/config/config.example.toml+++ b/config/config.example.toml@@ -122,7 +122,7 @@ tcp_user_timeout_ms = 5000 # Unacked-data timeout (ms); keep below connection_tihost = "127.0.0.1"port = 6379# username = "default" # Optional ACL username for authenticated Redis (Redis 6+ / Redis Cloud); requires `password`-# password = "" # Optional password for authenticated Redis (AUTH); leave unset for unauthenticated Redis+# primary_password = "" # Optional password for authenticated Redis (AUTH); leave unset for unauthenticated Redis# tls_enabled = true # Connect over TLS (`rediss://`); the server certificate is verified against the platform's trusted CA roots# tls_ca_certificate_path = "/path/to/redis_ca.pem" # When set, the server certificate is verified against the CA certificate(s) in this PEM file; when unset, against the platform's trusted CA rootspool_size = 5 # Number of connections to keep open@@ -1374,7 +1374,7 @@ forex_enabled = false # Enable or disable forex conversion for analytics[analytics.clickhouse]username = "" # Clickhouse username-password = "" # Clickhouse password (optional)+primary_password = "" # Clickhouse password (optional)host = "" # Clickhouse host in http(s)://<URL>:<PORT> formatdatabase_name = "" # Clickhouse database name@@ -1509,7 +1509,7 @@ enabled = false[opensearch.auth]auth = "basic"username = "admin"-password = "admin"+primary_password = "admin"region = "eu-central-1"[opensearch.indexes]@@ -1691,8 +1691,10 @@ connector_list = "worldpayvantiv"# Authentication to communicate between internal services using common_api_key, merchant id and profile id[internal_merchant_id_profile_id_auth]+primary_internal_api_key = ""+key_rotation_enabled = false+use_legacy_key_for_outbound = falseenabled = false # Enable or disable internal api key, merchant id and profile id based authentication-internal_api_key = "test_internal_api_key" # API key for internal merchant id and profile id based authentication[internal_services] # Internal services base urls and configspayments_base_url = "http://localhost:8080"diff --git a/config/deployments/drainer.toml b/config/deployments/drainer.tomlindex eb711200d2..61848a629f 100644--- a/config/deployments/drainer.toml+++ b/config/deployments/drainer.toml@@ -42,7 +42,7 @@ cluster_urls = ["redis.cluster.uri-1:8080", "redis.cluster.uri-2:4115"] # List odefault_ttl = 300host = "localhost"# username = "default" # Optional ACL username for authenticated Redis; requires `password`-# password = "" # Optional password for authenticated Redis (AUTH)+# primary_password = "" # Optional password for authenticated Redis (AUTH)# tls_enabled = true # Connect over TLS (`rediss://`); the server certificate is verified against the platform's trusted CA roots# tls_ca_certificate_path = "/path/to/redis_ca.pem" # When set, the server certificate is verified against the CA certificate(s) in this PEM file; when unset, against the platform's trusted CA rootspool_size = 5diff --git a/config/deployments/env_specific.toml b/config/deployments/env_specific.tomlindex 9a9f89b674..5f5a711188 100644--- a/config/deployments/env_specific.toml+++ b/config/deployments/env_specific.toml@@ -7,7 +7,7 @@ application_source = "main"[analytics.clickhouse]username = "clickhouse_username" # Clickhouse username-password = "clickhouse_password" # Clickhouse password (optional)+primary_password = "clickhouse_password" # Clickhouse password (optional)host = "http://localhost:8123" # Clickhouse host in http(s)://<URL>:<PORT> formatdatabase_name = "clickhouse_db_name" # Clickhouse database name@@ -33,8 +33,10 @@ max_lifetime = 1800 # Maximum lifetime in seconds before a connection is rhash_key = "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef" # API key hashing key.[internal_merchant_id_profile_id_auth]+primary_internal_api_key = ""+key_rotation_enabled = false+use_legacy_key_for_outbound = falseenabled = false-internal_api_key = "test_internal_api_key"[applepay_decrypt_keys]apple_pay_ppc = "APPLE_PAY_PAYMENT_PROCESSING_CERTIFICATE" # Payment Processing Certificate provided by Apple Pay (https://developer.apple.com/) Certificates, Identifiers & Profiles > Apple Pay Payment Processing Certificate@@ -103,7 +105,7 @@ connection = "plaintext" # currently plaintext and starttls are supportedhost = "127.0.0.1" # SOCKS5 proxy hostname or IPport = 1080 # SOCKS5 proxy portusername = "testuser" # SOCKS5 username, if the proxy requires auth-password = "testpass" # SOCKS5 password, if the proxy requires auth+primary_password = "testpass" # SOCKS5 password, if the proxy requires auth[events]source = "logs" # The event sink to push events supports kafka or logs (stdout)@@ -266,7 +268,7 @@ bypass_proxy_hosts = "localhost, cluster.local" # A comma-separated list of domahost = "127.0.0.1"port = 6379# username = "default" # Optional ACL username for authenticated Redis (Redis 6+ / Redis Cloud); requires `password`-# password = "" # Optional password for authenticated Redis (AUTH); leave unset for unauthenticated Redis+# primary_password = "" # Optional password for authenticated Redis (AUTH); leave unset for unauthenticated Redis# tls_enabled = true # Connect over TLS (`rediss://`); the server certificate is verified against the platform's trusted CA roots# tls_ca_certificate_path = "/path/to/redis_ca.pem" # When set, the server certificate is verified against the CA certificate(s) in this PEM file; when unset, against the platform's trusted CA rootspool_size = 5 # Number of connections to keep open@@ -361,7 +363,7 @@ enabled = false[opensearch.auth]auth = "basic"username = "admin"-password = "admin"+primary_password = "admin"region = "eu-central-1"[opensearch.indexes]diff --git a/config/development.toml b/config/development.tomlindex 4a56f09133..77de10aaa4 100644--- a/config/development.toml+++ b/config/development.toml@@ -112,7 +112,7 @@ port = 6379# an unauthenticated local Redis. `username` is optional (defaults to the# `default` user); setting `username` requires `password`.# username = "default"-# password = ""+# primary_password = ""# Connect over TLS (`rediss://`); required by most managed Redis offerings# (e.g. ElastiCache with encryption in transit, Redis Cloud with TLS).# When `tls_ca_certificate_path` is set, the server certificate is verified@@ -1562,7 +1562,7 @@ forex_enabled = false[analytics.clickhouse]username = "default"-# password = ""+# primary_password = ""host = "http://localhost:8123"database_name = "default"@@ -1598,7 +1598,7 @@ enabled = false[opensearch.auth]auth = "basic"username = "admin"-password = "0penS3arc#"+primary_password = "0penS3arc#"region = "eu-central-1"[opensearch.indexes]@@ -1764,8 +1764,10 @@ proxy_connector_http_status_code = false # If enabled, the http status code oconnector_list = "worldpayvantiv"[internal_merchant_id_profile_id_auth]+primary_internal_api_key = "test_internal_api_key"+key_rotation_enabled = false+use_legacy_key_for_outbound = falseenabled = false-internal_api_key = "test_internal_api_key"[internal_services]payments_base_url = "http://localhost:8080"diff --git a/config/docker_compose.toml b/config/docker_compose.tomlindex 0b582172c0..1b1d0aea2a 100644--- a/config/docker_compose.toml+++ b/config/docker_compose.toml@@ -158,7 +158,7 @@ vault_private_key = ""host = "redis-standalone"port = 6379# username = "default" # Optional ACL username for authenticated Redis; requires `password`-# password = "" # Optional password for authenticated Redis (AUTH)+# primary_password = "" # Optional password for authenticated Redis (AUTH)# tls_enabled = true # Connect over TLS (`rediss://`); the server certificate is verified against the platform's trusted CA roots# tls_ca_certificate_path = "/path/to/redis_ca.pem" # When set, the server certificate is verified against the CA certificate(s) in this PEM file; when unset, against the platform's trusted CA rootscluster_enabled = false@@ -1373,7 +1373,7 @@ forex_enabled = false # Enable or disable forex conversion for analytics[analytics.clickhouse]username = "default"-# password = ""+# primary_password = ""host = "http://localhost:8123"database_name = "default"@@ -1420,7 +1420,7 @@ enabled = false[opensearch.auth]auth = "basic"username = "admin"-password = "0penS3arc#"+primary_password = "0penS3arc#"region = "eu-central-1"[opensearch.indexes]@@ -1616,8 +1616,10 @@ connector_list = "worldpayvantiv"# Authentication to communicate between internal services using common_api_key, merchant id and profile id[internal_merchant_id_profile_id_auth]+primary_internal_api_key = "test_internal_api_key"+key_rotation_enabled = false+use_legacy_key_for_outbound = falseenabled = false # Enable or disable internal api key, merchant id and profile id based authentication-internal_api_key = "test_internal_api_key" # API key for internal merchant id and profile id based authentication[internal_services] # Internal services base urls and configspayments_base_url = "http://localhost:8080"diff --git a/crates/analytics/Cargo.toml b/crates/analytics/Cargo.tomlindex 10e54059ce..fcdfedf73d 100644--- a/crates/analytics/Cargo.toml+++ b/crates/analytics/Cargo.toml@@ -15,7 +15,7 @@ deja = ["dep:deja", "dep:opensearch_http", "dep:opensearch_reqwest", "common_uti# First party cratesapi_models = { version = "0.1.0", path = "../api_models", features = ["errors"] }common_enums = { version = "0.1.0", path = "../common_enums" }-common_utils = { version = "0.1.0", path = "../common_utils" }+common_utils = { version = "0.1.0", path = "../common_utils", features = ["async_ext"] }diesel_models = { version = "0.1.0", path = "../diesel_models", features = ["kv_store"], default-features = false }hyperswitch_interfaces = { version = "0.1.0", path = "../hyperswitch_interfaces", default-features = false }hyperswitch_masking = "0.0.1"diff --git a/crates/analytics/src/clickhouse.rs b/crates/analytics/src/clickhouse.rsindex 74dee8edf9..6d189ce93a 100644--- a/crates/analytics/src/clickhouse.rs+++ b/crates/analytics/src/clickhouse.rs@@ -1,8 +1,9 @@use std::sync::Arc;use actix_web::http::StatusCode;-use common_utils::errors::ParsingError;+use common_utils::{errors::ParsingError, ext_traits::AsyncExt};use error_stack::{report, Report, ResultExt};+use hyperswitch_masking::{PeekInterface, Secret};use router_env::logger;use time::PrimitiveDateTime;@@ -48,15 +49,39 @@ pub struct ClickhouseClient {#[derive(Clone, Debug, serde::Deserialize)]pub struct ClickhouseConfig {username: String,- password: Option<String>,+ primary_password: Option<Secret<String>>,host: String,}+impl ClickhouseConfig {+ pub(crate) async fn decrypt_credentials(+ self,+ client: &dyn hyperswitch_interfaces::secrets_interface::SecretManagementInterface,+ ) -> common_utils::errors::CustomResult<+ Self,+ hyperswitch_interfaces::secrets_interface::SecretsManagementError,+ > {+ let primary_password = self+ .primary_password+ .async_map(|secret| async move {+ client.get_secret(secret).await.map_err(|error| {+ error.attach_printable("analytics.clickhouse.primary_password")+ })+ })+ .await+ .transpose()?;+ Ok(Self {+ primary_password,+ ..self+ })+ }+}+impl Default for ClickhouseConfig {fn default() -> Self {Self {username: "default".to_string(),- password: None,+ primary_password: None,host: "http://localhost:8123".to_string(),}}@@ -74,7 +99,13 @@ impl ClickhouseClient {let response = client.post(&self.config.host).query(¶ms)- .basic_auth(self.config.username.clone(), self.config.password.clone())+ .basic_auth(+ self.config.username.clone(),+ self.config+ .primary_password+ .as_ref()+ .map(|password| password.peek()),+ ).body(format!("{query}\nFORMAT JSON")).send().awaitdiff --git a/crates/analytics/src/lib.rs b/crates/analytics/src/lib.rsindex 6cc621b51b..11e9b5f2c0 100644--- a/crates/analytics/src/lib.rs+++ b/crates/analytics/src/lib.rs@@ -1065,35 +1065,28 @@ impl SecretsHandler for AnalyticsConfig {value: SecretStateContainer<Self, SecuredSecret>,secret_management_client: &dyn SecretManagementInterface,) -> CustomResult<SecretStateContainer<Self, RawSecret>, SecretsManagementError> {- let analytics_config = value.get_inner();- let decrypted_password = match analytics_config {- // Todo: Perform kms decryption of clickhouse password- Self::Clickhouse { .. } => hyperswitch_masking::Secret::new(String::default()),- Self::Sqlx { sqlx, .. }- | Self::CombinedCkh { sqlx, .. }- | Self::CombinedSqlx { sqlx, .. } => {- secret_management_client- .get_secret(sqlx.password.clone())- .await?- }+ let decrypt_sqlx = |sqlx: Database| async move {+ let password = secret_management_client+ .get_secret(sqlx.password)+ .await+ .map_err(|error| error.attach_printable("analytics.sqlx.password"))?;+ Ok::<_, error_stack::Report<SecretsManagementError>>(Database { password, ..sqlx })};-- Ok(value.transition_state(|conf| match conf {+ let analytics_config = match value.get_inner().clone() {Self::Sqlx {sqlx,forex_enabled,} => Self::Sqlx {- sqlx: Database {- password: decrypted_password,- ..sqlx- },+ sqlx: decrypt_sqlx(sqlx).await?,forex_enabled,},Self::Clickhouse {clickhouse,forex_enabled,} => Self::Clickhouse {- clickhouse,+ clickhouse: clickhouse+ .decrypt_credentials(secret_management_client)+ .await?,forex_enabled,},Self::CombinedCkh {@@ -1101,11 +1094,10 @@ impl SecretsHandler for AnalyticsConfig {clickhouse,forex_enabled,} => Self::CombinedCkh {- sqlx: Database {- password: decrypted_password,- ..sqlx- },- clickhouse,+ sqlx: decrypt_sqlx(sqlx).await?,+ clickhouse: clickhouse+ .decrypt_credentials(secret_management_client)+ .await?,forex_enabled,},Self::CombinedSqlx {@@ -1113,14 +1105,14 @@ impl SecretsHandler for AnalyticsConfig {clickhouse,forex_enabled,} => Self::CombinedSqlx {- sqlx: Database {- password: decrypted_password,- ..sqlx- },- clickhouse,+ sqlx: decrypt_sqlx(sqlx).await?,+ clickhouse: clickhouse+ .decrypt_credentials(secret_management_client)+ .await?,forex_enabled,},- }))+ };+ Ok(value.transition_state(|_| analytics_config))}}diff --git a/crates/analytics/src/opensearch.rs b/crates/analytics/src/opensearch.rsindex 14f2b09be5..136ca52aea 100644--- a/crates/analytics/src/opensearch.rs+++ b/crates/analytics/src/opensearch.rs@@ -11,6 +11,10 @@ use common_utils::{types::TimeRange,};use error_stack::ResultExt;+use hyperswitch_interfaces::secrets_interface::{+ SecretManagementInterface, SecretsManagementError,+};+use hyperswitch_masking::ExposeInterface;use opensearch::{auth::Credentials,cert::CertificateValidation,@@ -37,8 +41,13 @@ mod recording;#[serde(tag = "auth")]#[serde(rename_all = "lowercase")]pub enum OpenSearchAuth {- Basic { username: String, password: String },- Aws { region: String },+ Basic {+ username: String,+ primary_password: String,+ },+ Aws {+ region: String,+ },}#[derive(Clone, Debug, serde::Deserialize)]@@ -86,7 +95,7 @@ impl Default for OpenSearchConfig {host: "https://localhost:9200".to_string(),auth: OpenSearchAuth::Basic {username: "admin".to_string(),- password: "admin".to_string(),+ primary_password: "admin".to_string(),},indexes: OpenSearchIndexes {payment_attempts: "hyperswitch-payment-attempt-events".to_string(),@@ -209,8 +218,12 @@ impl OpenSearchClient {pub async fn create(conf: &OpenSearchConfig) -> CustomResult<Self, OpenSearchError> {let url = Url::parse(&conf.host).map_err(|_| OpenSearchError::ConnectionError)?;let transport = match &conf.auth {- OpenSearchAuth::Basic { username, password } => {- let credentials = Credentials::Basic(username.clone(), password.clone());+ OpenSearchAuth::Basic {+ username,+ primary_password,+ ..+ } => {+ let credentials = Credentials::Basic(username.clone(), primary_password.clone());TransportBuilder::new(SingleNodeConnectionPool::new(url)).cert_validation(CertificateValidation::None).auth(credentials)@@ -422,14 +435,17 @@ impl OpenSearchAuth {use common_utils::{ext_traits::ConfigExt, fp_utils::when};match self {- Self::Basic { username, password } => {+ Self::Basic {+ username,+ primary_password,+ } => {when(username.is_default_or_empty(), || {Err(ApplicationError::InvalidConfigurationValueError("Opensearch Basic auth username must not be empty".into(),))})?;- when(password.is_default_or_empty(), || {+ when(primary_password.is_default_or_empty(), || {Err(ApplicationError::InvalidConfigurationValueError("Opensearch Basic auth password must not be empty".into(),))@@ -450,6 +466,30 @@ impl OpenSearchAuth {}impl OpenSearchConfig {+ pub async fn decrypt_credentials(+ self,+ client: &dyn SecretManagementInterface,+ ) -> CustomResult<Self, SecretsManagementError> {+ if !self.enabled {+ return Ok(self);+ }+ let auth = match self.auth {+ OpenSearchAuth::Basic {+ username,+ primary_password,+ } => OpenSearchAuth::Basic {+ username,+ primary_password: client+ .get_secret(primary_password.into())+ .await+ .map_err(|error| error.attach_printable("opensearch.auth.primary_password"))?+ .expose(),+ },+ auth @ OpenSearchAuth::Aws { .. } => auth,+ };+ Ok(Self { auth, ..self })+ }+pub async fn get_opensearch_client(&self) -> StorageResult<Option<OpenSearchClient>> {if !self.enabled {return Ok(None);diff --git a/crates/drainer/Cargo.toml b/crates/drainer/Cargo.tomlindex 5f30c5f9c0..e4f7bf1f81 100644--- a/crates/drainer/Cargo.toml+++ b/crates/drainer/Cargo.toml@@ -41,7 +41,7 @@ thiserror = "1.0.69"tokio = { version = "1.48.0", features = ["macros", "rt-multi-thread"] }# First Party Crates-common_utils = { version = "0.1.0", path = "../common_utils", features = ["signals", "diesel"] }+common_utils = { version = "0.1.0", path = "../common_utils", features = ["signals", "diesel", "async_ext"] }diesel_models = { version = "0.1.0", path = "../diesel_models", features = ["kv_store"], default-features = false }external_services = { version = "0.1.0", path = "../external_services" }hyperswitch_interfaces = { version = "0.1.0", path = "../hyperswitch_interfaces" }diff --git a/crates/drainer/src/secrets_transformers.rs b/crates/drainer/src/secrets_transformers.rsindex 0582ccd798..392b740b93 100644--- a/crates/drainer/src/secrets_transformers.rs+++ b/crates/drainer/src/secrets_transformers.rs@@ -1,4 +1,4 @@-use common_utils::errors::CustomResult;+use common_utils::{errors::CustomResult, ext_traits::AsyncExt};use hyperswitch_interfaces::secrets_interface::{secret_handler::SecretsHandler,secret_state::{RawSecret, SecretStateContainer, SecuredSecret},@@ -31,20 +31,35 @@ impl SecretsHandler for Database {pub async fn fetch_raw_secrets(conf: Settings<SecuredSecret>,secret_management_client: &dyn SecretManagementInterface,-) -> Settings<RawSecret> {+) -> CustomResult<Settings<RawSecret>, SecretsManagementError> {+ let redis = conf.redis;+ let primary_password = redis+ .primary_password+ .async_map(|secret| async move {+ secret_management_client+ .get_secret(secret)+ .await+ .map_err(|error| error.attach_printable("redis.primary_password"))+ })+ .await+ .transpose()?;+ let redis = redis_interface::RedisSettings {+ primary_password,+ ..redis+ };#[allow(clippy::expect_used)]let database = Database::convert_to_raw_secret(conf.master_database, secret_management_client).await.expect("Failed to decrypt database password");- Settings {+ Ok(Settings {server: conf.server,master_database: database,- redis: conf.redis,+ redis,log: conf.log,drainer: conf.drainer,encryption_management: conf.encryption_management,secrets_management: conf.secrets_management,multitenancy: conf.multitenancy,- }+ })}diff --git a/crates/drainer/src/settings.rs b/crates/drainer/src/settings.rsindex 331d419f8a..fec870d6ab 100644--- a/crates/drainer/src/settings.rs+++ b/crates/drainer/src/settings.rs@@ -46,8 +46,10 @@ impl AppState {.await.expect("Failed to create secret management client");- let raw_conf =- secrets_transformers::fetch_raw_secrets(conf, &*secret_management_client).await;+ #[allow(clippy::expect_used)]+ let raw_conf = secrets_transformers::fetch_raw_secrets(conf, &*secret_management_client)+ .await+ .expect("Failed to decrypt drainer configuration");#[allow(clippy::expect_used)]let encryption_client = raw_confdiff --git a/crates/external_services/Cargo.toml b/crates/external_services/Cargo.tomlindex d2f5266b31..f8240dd354 100644--- a/crates/external_services/Cargo.toml+++ b/crates/external_services/Cargo.toml@@ -97,7 +97,7 @@ superposition_sdk = { version = "0.118.2", optional = true }# First party crates-common_utils = { version = "0.1.0", path = "../common_utils" }+common_utils = { version = "0.1.0", path = "../common_utils", features = ["async_ext"] }common_enums = { version = "0.1.0", path = "../common_enums" }hyperswitch_interfaces = { version = "0.1.0", path = "../hyperswitch_interfaces", default-features = false }cloud_services = { version = "0.1.0", path = "../cloud_services", optional = true }diff --git a/crates/external_services/src/email.rs b/crates/external_services/src/email.rsindex f9ba0b789d..80cc4d0c15 100644--- a/crates/external_services/src/email.rs+++ b/crates/external_services/src/email.rs@@ -206,6 +206,23 @@ pub struct EmailSettings {}impl EmailSettings {+ #[allow(missing_docs)]+ pub async fn decrypt_credentials(+ self,+ client: &dyn hyperswitch_interfaces::secrets_interface::SecretManagementInterface,+ ) -> CustomResult<Self, hyperswitch_interfaces::secrets_interface::SecretsManagementError> {+ let client_config = match self.client_config {+ EmailClientConfigs::Smtp { smtp } => EmailClientConfigs::Smtp {+ smtp: smtp.decrypt_credentials(client).await?,+ },+ client_config => client_config,+ };+ Ok(Self {+ client_config,+ ..self+ })+ }+/// Validation for the Email client specific configurationspub fn validate(&self) -> Result<(), &'static str> {match &self.client_config {diff --git a/crates/external_services/src/email/smtp.rs b/crates/external_services/src/email/smtp.rsindex 3dc076487c..148dd4527f 100644--- a/crates/external_services/src/email/smtp.rs+++ b/crates/external_services/src/email/smtp.rs@@ -5,7 +5,7 @@pub use cloud_services::email::smtp::{SmtpConnection, SmtpError};use cloud_services::email::{smtp as shared, EmailMessage};-use common_utils::{errors::CustomResult, pii};+use common_utils::{errors::CustomResult, ext_traits::AsyncExt, pii};use hyperswitch_masking::{PeekInterface, Secret};use crate::{@@ -47,7 +47,7 @@ pub struct SmtpServerConfig {/// Username name of the SMTP serverpub username: Option<Secret<String>>,/// Password of the SMTP server- pub password: Option<Secret<String>>,+ pub primary_password: Option<Secret<String>>,/// Connection type of the SMTP server#[serde(default)]pub connection: SmtpConnection,@@ -66,27 +66,73 @@ pub struct Socks5Config {/// SOCKS5 username, if the proxy requires auth.pub username: Option<Secret<String>>,/// SOCKS5 password, if the proxy requires auth.- pub password: Option<Secret<String>>,+ pub primary_password: Option<Secret<String>>,}impl SmtpServerConfig {+ #[allow(missing_docs)]+ pub async fn decrypt_credentials(+ self,+ client: &dyn hyperswitch_interfaces::secrets_interface::SecretManagementInterface,+ ) -> CustomResult<Self, hyperswitch_interfaces::secrets_interface::SecretsManagementError> {+ let primary_password = self+ .primary_password+ .async_map(|secret| async move {+ client+ .get_secret(secret)+ .await+ .map_err(|error| error.attach_printable("email.smtp.primary_password"))+ })+ .await+ .transpose()?;+ let socks5 = self+ .socks5+ .async_map(|socks5| async move {+ let primary_password = socks5+ .primary_password+ .async_map(|secret| async move {+ client.get_secret(secret).await.map_err(|error| {+ error.attach_printable("email.smtp.socks5.primary_password")+ })+ })+ .await+ .transpose()?;+ Ok::<+ _,+ error_stack::Report<+ hyperswitch_interfaces::secrets_interface::SecretsManagementError,+ >,+ >(Socks5Config {+ primary_password,+ ..socks5+ })+ })+ .await+ .transpose()?;+ Ok(Self {+ primary_password,+ socks5,+ ..self+ })+ }+/// Validation for the SMTP server client specific configspub fn validate(&self) -> Result<(), &'static str> {use common_utils::{ext_traits::ConfigExt, fp_utils::when};when(self.host.is_default_or_empty(), || {Err("email.smtp.host must not be empty")})?;- self.username.clone().zip(self.password.clone()).map_or(- Ok(()),- |(username, password)| {+ self.username+ .clone()+ .zip(self.primary_password.clone())+ .map_or(Ok(()), |(username, password)| {when(username.peek().is_default_or_empty(), || {Err("email.smtp.username must not be empty")})?;when(password.peek().is_default_or_empty(), || {- Err("email.smtp.password must not be empty")+ Err("email.smtp.primary_password must not be empty")})- },- )?;+ })?;self.socks5.as_ref().map_or(Ok(()), Socks5Config::validate)}@@ -96,7 +142,10 @@ impl SmtpServerConfig {port: self.port,timeout: self.timeout,username: self.username.as_ref().map(|value| value.peek().to_owned()),- password: self.password.as_ref().map(|value| value.peek().to_owned()),+ password: self+ .primary_password+ .as_ref()+ .map(|value| value.peek().to_owned()),connection: self.connection.clone(),socks5: self.socks5.as_ref().map(|socks5| shared::Socks5Config {host: socks5.host.clone(),@@ -106,7 +155,7 @@ impl SmtpServerConfig {.as_ref().map(|value| value.peek().to_owned()),password: socks5- .password+ .primary_password.as_ref().map(|value| value.peek().to_owned()),}),@@ -123,13 +172,13 @@ impl Socks5Config {when(self.port == 0, || {Err("email.smtp.socks5.port must not be zero")})?;- match (self.username.as_ref(), self.password.as_ref()) {+ match (self.username.as_ref(), self.primary_password.as_ref()) {(Some(username), Some(password)) => {when(username.peek().is_default_or_empty(), || {Err("email.smtp.socks5.username must not be empty")})?;when(password.peek().is_default_or_empty(), || {- Err("email.smtp.socks5.password must not be empty")+ Err("email.smtp.socks5.primary_password must not be empty")})}(None, None) => Ok(()),diff --git a/crates/hyperswitch_domain_models/src/connector_endpoints.rs b/crates/hyperswitch_domain_models/src/connector_endpoints.rsindex 3fa11b7ccf..049e69dd09 100644--- a/crates/hyperswitch_domain_models/src/connector_endpoints.rs+++ b/crates/hyperswitch_domain_models/src/connector_endpoints.rs@@ -224,8 +224,6 @@ impl NoParams {pub struct ConnectorParamsWithKeys {/// base urlpub base_url: String,- /// api key- pub api_key: Secret<String>,/// merchant IDpub merchant_id: Secret<String>,}diff --git a/crates/hyperswitch_interfaces/Cargo.toml b/crates/hyperswitch_interfaces/Cargo.tomlindex 5bec9b6ac4..5b4f6cf339 100644--- a/crates/hyperswitch_interfaces/Cargo.toml+++ b/crates/hyperswitch_interfaces/Cargo.toml@@ -30,6 +30,7 @@ reqwest = "0.13.5"serde = { version = "1.0.219", features = ["derive"] }serde_json = "1.0.140"strum = { version = "0.26", features = ["derive"] }+subtle = "2.6.1"thiserror = "1.0.69"time = "0.3.41"tonic = "0.14"diff --git a/crates/hyperswitch_interfaces/src/configs.rs b/crates/hyperswitch_interfaces/src/configs.rsindex e02858a8e9..e19b0a8c6b 100644--- a/crates/hyperswitch_interfaces/src/configs.rs+++ b/crates/hyperswitch_interfaces/src/configs.rs@@ -1,9 +1,12 @@-use common_utils::{crypto::Encryptable, errors::CustomResult, id_type};+use common_utils::{crypto::Encryptable, errors::CustomResult, ext_traits::ConfigExt, id_type};pub use hyperswitch_domain_models::{connector_endpoints::Connectors, errors::api_error_response, merchant_connector_account,};use hyperswitch_masking::{PeekInterface, Secret};use serde::Deserialize;+use subtle::ConstantTimeEq;++use crate::secrets_interface::SecretsManagementError;#[allow(missing_docs)]#[derive(Debug, Clone)]@@ -87,7 +90,82 @@ impl Default for GlobalTenant {#[serde(default)]pub struct InternalMerchantIdProfileIdAuthSettings {pub enabled: bool,- pub internal_api_key: Secret<String>,+ pub internal_api_key: Option<Secret<String>>,+ pub primary_internal_api_key: Secret<String>,+ pub key_rotation_enabled: bool,+ pub use_legacy_key_for_outbound: bool,+}++#[allow(missing_docs)]+impl InternalMerchantIdProfileIdAuthSettings {+ pub async fn decrypt_credentials(+ self,+ client: &dyn crate::secrets_interface::SecretManagementInterface,+ ) -> CustomResult<Self, SecretsManagementError> {+ let legacy_key_required = self.key_rotation_enabled || self.use_legacy_key_for_outbound;+ let legacy_key_configured = self+ .internal_api_key+ .as_ref()+ .is_some_and(|key| !key.is_default_or_empty());+ let primary_internal_api_key = if self.primary_internal_api_key.is_default_or_empty() {+ if self.enabled || legacy_key_required || legacy_key_configured {+ return Err(+ error_stack::Report::new(SecretsManagementError::FetchSecretFailed)+ .attach_printable(+ "Internal authentication requires primary_internal_api_key",+ ),+ );+ }+ self.primary_internal_api_key+ } else {+ client+ .get_secret(self.primary_internal_api_key)+ .await+ .map_err(|error| {+ error.attach_printable(+ "internal_merchant_id_profile_id_auth.primary_internal_api_key",+ )+ })?+ };+ if legacy_key_required && !legacy_key_configured {+ return Err(+ error_stack::Report::new(SecretsManagementError::FetchSecretFailed)+ .attach_printable(+ "Legacy inbound or outbound authentication requires internal_api_key",+ ),+ );+ }+ let internal_api_key = if legacy_key_required {+ self.internal_api_key+ } else {+ None+ };+ Ok(Self {+ primary_internal_api_key,+ internal_api_key,+ ..self+ })+ }++ pub fn accepts_api_key(&self, candidate: &str) -> bool {+ let primary_key = &self.primary_internal_api_key;+ if primary_key.is_default_or_empty() {+ return false;+ }+ let matches = |key: &Secret<String>| {+ !key.is_default_or_empty()+ && bool::from(candidate.as_bytes().ct_eq(key.peek().as_bytes()))+ };+ matches(primary_key)+ || (self.key_rotation_enabled && self.internal_api_key.as_ref().is_some_and(matches))+ }++ pub fn outbound_api_key(&self) -> &Secret<String> {+ self.internal_api_key+ .as_ref()+ .filter(|_| self.use_legacy_key_for_outbound)+ .unwrap_or(&self.primary_internal_api_key)+ }}#[allow(missing_docs)]diff --git a/crates/payment_methods/src/configs.rs b/crates/payment_methods/src/configs.rsindex cbe7c412ca..4e91deca57 100644--- a/crates/payment_methods/src/configs.rs+++ b/crates/payment_methods/src/configs.rs@@ -16,6 +16,30 @@ pub struct MicroServicesConfig {pub authentication_service: Option<AuthenticationServiceConfig>,}+impl MicroServicesConfig {+ pub async fn decrypt_credentials(+ self,+ client: &dyn hyperswitch_interfaces::secrets_interface::SecretManagementInterface,+ ) -> common_utils::errors::CustomResult<+ Self,+ hyperswitch_interfaces::secrets_interface::SecretsManagementError,+ > {+ let authentication_service = match self.authentication_service {+ Some(service) => Some(AuthenticationServiceConfig {+ api_key: client.get_secret(service.api_key).await.map_err(|error| {+ error.attach_printable("micro_services.authentication_service.api_key")+ })?,+ ..service+ }),+ None => None,+ };+ Ok(Self {+ authentication_service,+ ..self+ })+ }+}+/// Configuration for the authentication microservice.#[derive(Debug, Deserialize, Clone, Default)]#[serde(default)]diff --git a/crates/redis_interface/src/test.rs b/crates/redis_interface/src/test.rsindex 6e918dd228..4b44441b86 100644--- a/crates/redis_interface/src/test.rs+++ b/crates/redis_interface/src/test.rs@@ -2409,7 +2409,7 @@ fn auth_settings_from_env() -> Option<RedisSettings> {host,port,username,- password: Some(password.into()),+ primary_password: Some(password.into()),..RedisSettings::default()})}@@ -2508,7 +2508,7 @@ async fn test_authenticated_connection_wrong_password_fails() {return true;};- settings.password = Some("definitely_the_wrong_password".to_string().into());+ settings.primary_password = Some("definitely_the_wrong_password".to_string().into());test_connection(&settings).await.is_err()})@@ -2572,7 +2572,7 @@ fn tls_settings_from_env() -> Option<RedisSettings> {host,port,username,- password: password.map(Into::into),+ primary_password: password.map(Into::into),tls_enabled: true,tls_ca_certificate_path,..RedisSettings::default()diff --git a/crates/redis_interface/src/types.rs b/crates/redis_interface/src/types.rsindex 57ee508f47..9b14514b46 100644--- a/crates/redis_interface/src/types.rs+++ b/crates/redis_interface/src/types.rs@@ -36,7 +36,7 @@ pub struct RedisSettings {pub username: Option<String>,/// Password for Redis `AUTH` / ACL authentication./// When unset, the connection handshake is unauthenticated.- pub password: Option<Secret<String>>,+ pub primary_password: Option<Secret<String>>,/// When `true`, connect over TLS (the `rediss://` scheme). Required by/// most managed Redis offerings, e.g. AWS ElastiCache with encryption in/// transit, Azure Cache for Redis, or Redis Cloud with TLS enabled.@@ -102,7 +102,7 @@ impl RedisSettings {////// Emptiness is enforced by [`Self::validate`], not here.pub(crate) fn auth_password(&self) -> Option<&str> {- self.password+ self.primary_password.as_ref().map(|password| password.peek().as_str())}@@ -147,12 +147,12 @@ impl RedisSettings {)?;when(- self.password+ self.primary_password.as_ref().is_some_and(|password| password.is_default_or_empty()),|| {Err(errors::RedisError::InvalidConfiguration(- "Redis `password` must not be empty when specified".into(),+ "Redis `primary_password` must not be empty when specified".into(),))},)?;@@ -161,7 +161,7 @@ impl RedisSettings {self.auth_username().is_some() && self.auth_password().is_none(),|| {Err(errors::RedisError::InvalidConfiguration(- "Redis `password` must be specified when `username` is set".into(),+ "Redis `primary_password` must be specified when `username` is set".into(),))},)?;@@ -226,7 +226,7 @@ impl Default for RedisSettings {host: "127.0.0.1".to_string(),port: 6379,username: None,- password: None,+ primary_password: None,tls_enabled: false,tls_ca_certificate_path: None,cluster_enabled: false,@@ -592,7 +592,7 @@ mod tests {fn test_redis_settings_validate_username_without_password() {let settings = RedisSettings {username: Some("app_user".to_string()),- password: None,+ primary_password: None,..RedisSettings::default()};assert!(settings.validate().is_err());@@ -602,7 +602,7 @@ mod tests {fn test_redis_settings_validate_username_with_password() {let settings = RedisSettings {username: Some("app_user".to_string()),- password: Some("secret".to_string().into()),+ primary_password: Some("secret".to_string().into()),..RedisSettings::default()};assert!(settings.validate().is_ok());@@ -611,7 +611,7 @@ mod tests {#[test]fn test_redis_settings_validate_password_only() {let settings = RedisSettings {- password: Some("secret".to_string().into()),+ primary_password: Some("secret".to_string().into()),..RedisSettings::default()};assert!(settings.validate().is_ok());@@ -621,7 +621,7 @@ mod tests {fn test_redis_settings_validate_empty_username_rejected() {let settings = RedisSettings {username: Some(String::new()),- password: Some("secret".to_string().into()),+ primary_password: Some("secret".to_string().into()),..RedisSettings::default()};assert!(settings.validate().is_err());@@ -631,7 +631,7 @@ mod tests {fn test_redis_settings_validate_whitespace_username_rejected() {let settings = RedisSettings {username: Some(" ".to_string()),- password: Some("secret".to_string().into()),+ primary_password: Some("secret".to_string().into()),..RedisSettings::default()};assert!(settings.validate().is_err());@@ -640,7 +640,7 @@ mod tests {#[test]fn test_redis_settings_validate_empty_password_rejected() {let settings = RedisSettings {- password: Some(String::new().into()),+ primary_password: Some(String::new().into()),..RedisSettings::default()};assert!(settings.validate().is_err());@@ -724,7 +724,7 @@ mod tests {#[test]fn test_redis_settings_password_masked_in_debug() {let settings = RedisSettings {- password: Some("super_secret".to_string().into()),+ primary_password: Some("super_secret".to_string().into()),..RedisSettings::default()};let debug_output = format!("{settings:?}");diff --git a/crates/router/src/configs/secrets_transformers.rs b/crates/router/src/configs/secrets_transformers.rsindex 4c2816d77b..dc9e220a62 100644--- a/crates/router/src/configs/secrets_transformers.rs+++ b/crates/router/src/configs/secrets_transformers.rs@@ -478,7 +478,40 @@ impl SecretsHandler for settings::AccountUpdaterConfig {pub(crate) async fn fetch_raw_secrets(conf: Settings<SecuredSecret>,secret_management_client: &dyn SecretManagementInterface,-) -> Settings<RawSecret> {+) -> CustomResult<Settings<RawSecret>, SecretsManagementError> {+ #[cfg(feature = "olap")]+ let opensearch = conf+ .opensearch+ .decrypt_credentials(secret_management_client)+ .await?;+ let micro_services = conf+ .micro_services+ .decrypt_credentials(secret_management_client)+ .await?;+ let redis = conf.redis;+ let primary_password = redis+ .primary_password+ .async_map(|secret| async move {+ secret_management_client+ .get_secret(secret)+ .await+ .map_err(|error| error.attach_printable("redis.primary_password"))+ })+ .await+ .transpose()?;+ let redis = redis_interface::RedisSettings {+ primary_password,+ ..redis+ };+ let internal_merchant_id_profile_id_auth = conf+ .internal_merchant_id_profile_id_auth+ .decrypt_credentials(secret_management_client)+ .await?;+ #[cfg(feature = "email")]+ let email = conf+ .decrypt_credentials(secret_management_client)+ .await?;#[allow(clippy::expect_used)]let master_database =settings::Database::convert_to_raw_secret(conf.master_database, secret_management_client)@@ -688,14 +721,14 @@ pub(crate) async fn fetch_raw_secrets(open_router};- Settings {+ Ok(Settings {server: conf.server,application_source: conf.application_source,sage,master_database,accounts_database,global_database,- redis: conf.redis,+ redis,cache: conf.cache,log: conf.log,#[cfg(feature = "deja")]@@ -731,7 +764,7 @@ pub(crate) async fn fetch_raw_secrets(#[cfg(feature = "dummy_connector")]dummy_connector: conf.dummy_connector,#[cfg(feature = "email")]- email: conf.email,+ email,user: conf.user,oidc,mandates: conf.mandates,@@ -766,7 +799,7 @@ pub(crate) async fn fetch_raw_secrets(#[cfg(feature = "olap")]analytics,#[cfg(feature = "olap")]- opensearch: conf.opensearch,+ opensearch,#[cfg(feature = "kv_store")]kv_config: conf.kv_config,#[cfg(feature = "frm")]@@ -803,18 +836,18 @@ pub(crate) async fn fetch_raw_secrets(debit_routing_config: conf.debit_routing_config,clone_connector_allowlist: conf.clone_connector_allowlist,merchant_id_auth: conf.merchant_id_auth,- internal_merchant_id_profile_id_auth: conf.internal_merchant_id_profile_id_auth,+ internal_merchant_id_profile_id_auth,infra_values: conf.infra_values,enhancement: conf.enhancement,proxy_status_mapping: conf.proxy_status_mapping,trace_header: conf.trace_header,internal_services: conf.internal_services,- micro_services: conf.micro_services,+ micro_services,superposition,offer_engine,comparison_service: conf.comparison_service,authentication_service_enabled_connectors: conf.authentication_service_enabled_connectors,save_payment_method_on_session: conf.save_payment_method_on_session,account_updater,- }+ })}diff --git a/crates/router/src/core/payment_methods/transformers.rs b/crates/router/src/core/payment_methods/transformers.rsindex 01cdafee59..a15e547045 100644--- a/crates/router/src/core/payment_methods/transformers.rs+++ b/crates/router/src/core/payment_methods/transformers.rs@@ -1410,7 +1410,7 @@ pub async fn call_modular_payment_method_update(state.conf.internal_merchant_id_profile_id_auth- .internal_api_key+ .outbound_api_key().clone().expose().to_string()@@ -2159,10 +2159,10 @@ pub async fn retrieve_pm_modular_service_call(profile_id: &id_type::ProfileId,payment_method_fetch_req: RetrievePaymentMethodV1Request,) -> CustomResult<RetrievePaymentMethodResponse, errors::ApiErrorResponse> {- let internal_api_key = &state+ let internal_api_key = state.conf.internal_merchant_id_profile_id_auth- .internal_api_key;+ .outbound_api_key();let mut parent_headers = Headers::new();parent_headers.insert((headers::X_PROFILE_ID.to_string(),@@ -2429,10 +2429,10 @@ pub async fn list_customer_payment_methods_from_modular_service(customer_id: id_type::GlobalCustomerId,) -> CustomResult<Vec<payment_methods::types::PaymentMethodResponseItemV1>, errors::ApiErrorResponse>{- let internal_api_key = &state+ let internal_api_key = state.conf.internal_merchant_id_profile_id_auth- .internal_api_key;+ .outbound_api_key();let mut parent_headers = Headers::new();parent_headers.insert((headers::X_PROFILE_ID.to_string(),@@ -2490,10 +2490,10 @@ pub async fn create_pm_modular_service_call(profile_id: &id_type::ProfileId,payment_method_create_req: CreatePaymentMethodV1Request,) -> CustomResult<CreatePaymentMethodResponse, errors::ApiErrorResponse> {- let internal_api_key = &state+ let internal_api_key = state.conf.internal_merchant_id_profile_id_auth- .internal_api_key;+ .outbound_api_key();let mut parent_headers = Headers::new();parent_headers.insert((headers::X_PROFILE_ID.to_string(),diff --git a/crates/router/src/core/payments/vault_session.rs b/crates/router/src/core/payments/vault_session.rsindex bbbc284c03..83d5859d0e 100644--- a/crates/router/src/core/payments/vault_session.rs+++ b/crates/router/src/core/payments/vault_session.rs@@ -241,10 +241,10 @@ async fn call_internal_pm_session_create_for_vault(// (provider) merchant whose profile carries the external vault configuration.let merchant_id = &profile.merchant_id;let profile_id = profile.get_id();- let internal_api_key = &state+ let internal_api_key = state.conf.internal_merchant_id_profile_id_auth- .internal_api_key;+ .outbound_api_key();let mut headers = Headers::new();headers.insert((diff --git a/crates/router/src/routes/app.rs b/crates/router/src/routes/app.rsindex b8d9d7f687..927e3f8308 100644--- a/crates/router/src/routes/app.rs+++ b/crates/router/src/routes/app.rs@@ -482,11 +482,13 @@ impl AppState {.await.expect("Failed to create secret management client");+ #[allow(clippy::expect_used)]let conf = Box::pin(secrets_transformers::fetch_raw_secrets(conf,&*secret_management_client,))- .await;+ .await+ .expect("Failed to decrypt application configuration");#[allow(clippy::expect_used)]let encryption_client = confdiff --git a/crates/router/src/services/authentication.rs b/crates/router/src/services/authentication.rsindex c956dd1c03..065a4cd340 100644--- a/crates/router/src/services/authentication.rs+++ b/crates/router/src/services/authentication.rs@@ -2709,11 +2709,9 @@ impl<F> InternalMerchantIdProfileIdAuth<F> {(internal_api_key, merchant_id, profile_id){let config = state.conf();- if internal_api_key- != *config- .internal_merchant_id_profile_id_auth- .internal_api_key- .peek()+ if !config+ .internal_merchant_id_profile_id_auth+ .accepts_api_key(&internal_api_key){return Err(errors::ApiErrorResponse::Unauthorized).attach_printable("Internal API key authentication failed");@@ -2856,12 +2854,10 @@ wherematch internal_api_key {Some(key) => {- if key- == *state- .conf()- .internal_merchant_id_profile_id_auth- .internal_api_key- .peek()+ if state+ .conf()+ .internal_merchant_id_profile_id_auth+ .accepts_api_key(&key){Ok(((), AuthenticationType::InternalApiKey))} else {diff --git a/crates/subscriptions/src/core/payments_api_client.rs b/crates/subscriptions/src/core/payments_api_client.rsindex 32296d5394..1826c33cfc 100644--- a/crates/subscriptions/src/core/payments_api_client.rs+++ b/crates/subscriptions/src/core/payments_api_client.rs@@ -33,7 +33,7 @@ impl PaymentsApiClient {state.conf.internal_merchant_id_profile_id_auth- .internal_api_key+ .outbound_api_key().clone(),),),diff --git a/loadtest/config/development.toml b/loadtest/config/development.tomlindex d879311463..89fcc02192 100644--- a/loadtest/config/development.toml+++ b/loadtest/config/development.toml@@ -1021,7 +1021,7 @@ id_reuse_strategy = "ignore_incoming" # Options: "ignore_incoming" (default) or# Authentication to communicate between internal services using common_api_key, merchant id and profile id[internal_merchant_id_profile_id_auth]enabled = false # Enable or disable internal api key, merchant id and profile id based authentication-internal_api_key = "test_internal_api_key" # API key for internal merchant id and profile id based authentication+primary_internal_api_key = "test_internal_api_key" # API key for internal merchant id and profile id based authentication[internal_services] # Internal services base urls and configspayments_base_url = "http://localhost:8080"