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

16.2 KB
Raw Blame
use common_utils::ext_traits::ConfigExt;
use hyperswitch_masking::PeekInterface;
use storage_impl::errors::ApplicationError;

use crate::consts::MIN_IDLE_SESSION_TIMEOUT_IN_SECS;

impl super::settings::Secrets {
    pub fn validate(&self) -> Result<(), ApplicationError> {
        use common_utils::fp_utils::when;

        when(self.jwt_secret.is_default_or_empty(), || {
            Err(ApplicationError::InvalidConfigurationValueError(
                "JWT secret must not be empty".into(),
            ))
        })?;

        when(self.admin_api_key.is_default_or_empty(), || {
            Err(ApplicationError::InvalidConfigurationValueError(
                "admin API key must not be empty".into(),
            ))
        })?;

        when(self.master_enc_key.is_default_or_empty(), || {
            Err(ApplicationError::InvalidConfigurationValueError(
                "Master encryption key must not be empty".into(),
            ))
        })
    }
}

impl super::settings::UserSettings {
    pub fn validate(&self) -> Result<(), ApplicationError> {
        use common_utils::fp_utils::when;

        when(
            self.idle_session_timeout_in_secs
                .is_some_and(|idle_timeout_in_secs| {
                    idle_timeout_in_secs < MIN_IDLE_SESSION_TIMEOUT_IN_SECS
                }),
            || {
                Err(ApplicationError::InvalidConfigurationValueError(format!(
                    "user idle session timeout must be at least \
                     {MIN_IDLE_SESSION_TIMEOUT_IN_SECS} seconds when set"
                )))
            },
        )
    }
}

impl super::settings::Locker {
    pub fn validate(&self) -> Result<(), ApplicationError> {
        use common_utils::fp_utils::when;

        when(!self.mock_locker && self.host.is_default_or_empty(), || {
            Err(ApplicationError::InvalidConfigurationValueError(
                "locker host must not be empty when mock locker is disabled".into(),
            ))
        })
    }
}

impl super::settings::Server {
    pub fn validate(&self) -> Result<(), ApplicationError> {
        use common_utils::fp_utils::when;

        when(self.host.is_default_or_empty(), || {
            Err(ApplicationError::InvalidConfigurationValueError(
                "server host must not be empty".into(),
            ))
        })?;

        when(self.workers == 0, || {
            Err(ApplicationError::InvalidConfigurationValueError(
                "number of workers must be greater than 0".into(),
            ))
        })
    }
}

impl super::settings::Database {
    pub fn validate(&self) -> Result<(), ApplicationError> {
        use common_utils::fp_utils::when;

        when(self.host.is_default_or_empty(), || {
            Err(ApplicationError::InvalidConfigurationValueError(
                "database host must not be empty".into(),
            ))
        })?;

        when(self.dbname.is_default_or_empty(), || {
            Err(ApplicationError::InvalidConfigurationValueError(
                "database name must not be empty".into(),
            ))
        })?;

        when(self.username.is_default_or_empty(), || {
            Err(ApplicationError::InvalidConfigurationValueError(
                "database user username must not be empty".into(),
            ))
        })?;

        when(self.password.is_default_or_empty(), || {
            Err(ApplicationError::InvalidConfigurationValueError(
                "database user password must not be empty".into(),
            ))
        })
    }
}

impl super::settings::SupportedConnectors {
    pub fn validate(&self) -> Result<(), ApplicationError> {
        common_utils::fp_utils::when(self.wallets.is_empty(), || {
            Err(ApplicationError::InvalidConfigurationValueError(
                "list of connectors supporting wallets must not be empty".into(),
            ))
        })
    }
}

impl super::settings::CorsSettings {
    pub fn validate(&self) -> Result<(), ApplicationError> {
        common_utils::fp_utils::when(self.wildcard_origin && !self.origins.is_empty(), || {
            Err(ApplicationError::InvalidConfigurationValueError(
                "Allowed Origins must be empty when wildcard origin is true".to_string(),
            ))
        })?;

        common_utils::fp_utils::when(!self.wildcard_origin && self.origins.is_empty(), || {
            Err(ApplicationError::InvalidConfigurationValueError(
                "Allowed origins must not be empty. Please either enable wildcard origin or provide Allowed Origin".to_string(),
            ))
        })
    }
}

#[cfg(feature = "kv_store")]
impl super::settings::DrainerSettings {
    pub fn validate(&self) -> Result<(), ApplicationError> {
        common_utils::fp_utils::when(self.stream_name.is_default_or_empty(), || {
            Err(ApplicationError::InvalidConfigurationValueError(
                "drainer stream name must not be empty".into(),
            ))
        })
    }
}

impl super::settings::ApiKeys {
    pub fn validate(&self) -> Result<(), ApplicationError> {
        use common_utils::fp_utils::when;

        when(self.hash_key.peek().is_empty(), || {
            Err(ApplicationError::InvalidConfigurationValueError(
                "API key hashing key must not be empty".into(),
            ))
        })?;

        #[cfg(feature = "email")]
        when(self.expiry_reminder_days.is_empty(), || {
            Err(ApplicationError::InvalidConfigurationValueError(
                "API key expiry reminder days must not be empty".into(),
            ))
        })?;

        Ok(())
    }
}

impl super::settings::LockSettings {
    pub fn validate(&self) -> Result<(), ApplicationError> {
        use common_utils::fp_utils::when;

        when(self.redis_lock_expiry_seconds.is_default_or_empty(), || {
            Err(ApplicationError::InvalidConfigurationValueError(
                "redis_lock_expiry_seconds must not be empty or 0".into(),
            ))
        })?;

        when(
            self.delay_between_retries_in_milliseconds
                .is_default_or_empty(),
            || {
                Err(ApplicationError::InvalidConfigurationValueError(
                    "delay_between_retries_in_milliseconds must not be empty or 0".into(),
                ))
            },
        )?;

        when(self.lock_retries.is_default_or_empty(), || {
            Err(ApplicationError::InvalidConfigurationValueError(
                "lock_retries must not be empty or 0".into(),
            ))
        })
    }
}

impl super::settings::WebhooksSettings {
    pub fn validate(&self) -> Result<(), ApplicationError> {
        use common_utils::fp_utils::when;

        when(self.redis_lock_expiry_seconds.is_default_or_empty(), || {
            Err(ApplicationError::InvalidConfigurationValueError(
                "redis_lock_expiry_seconds must not be empty or 0".into(),
            ))
        })
    }
}

impl super::settings::GenericLinkEnvConfig {
    pub fn validate(&self) -> Result<(), ApplicationError> {
        use common_utils::fp_utils::when;

        when(self.expiry == 0, || {
            Err(ApplicationError::InvalidConfigurationValueError(
                "link's expiry should not be 0".into(),
            ))
        })
    }
}

impl super::settings::CellInformation {
    pub fn validate(&self) -> Result<(), ApplicationError> {
        use common_utils::fp_utils::when;

        when(self == &Self::default(), || {
            Err(ApplicationError::InvalidConfigurationValueError(
                "CellId cannot be set to a default".into(),
            ))
        })
    }
}

impl super::settings::NetworkTokenizationService {
    pub fn validate(&self) -> Result<(), ApplicationError> {
        use common_utils::fp_utils::when;

        when(self.token_service_api_key.is_default_or_empty(), || {
            Err(ApplicationError::InvalidConfigurationValueError(
                "token_service_api_key must not be empty".into(),
            ))
        })?;

        when(self.public_key.is_default_or_empty(), || {
            Err(ApplicationError::InvalidConfigurationValueError(
                "public_key must not be empty".into(),
            ))
        })?;

        when(self.key_id.is_default_or_empty(), || {
            Err(ApplicationError::InvalidConfigurationValueError(
                "key_id must not be empty".into(),
            ))
        })?;

        when(self.private_key.is_default_or_empty(), || {
            Err(ApplicationError::InvalidConfigurationValueError(
                "private_key must not be empty".into(),
            ))
        })?;

        when(
            self.webhook_source_verification_key.is_default_or_empty(),
            || {
                Err(ApplicationError::InvalidConfigurationValueError(
                    "webhook_source_verification_key must not be empty".into(),
                ))
            },
        )
    }
}

impl super::settings::PazeDecryptConfig {
    pub fn validate(&self) -> Result<(), ApplicationError> {
        use common_utils::fp_utils::when;

        when(self.paze_private_key.is_default_or_empty(), || {
            Err(ApplicationError::InvalidConfigurationValueError(
                "paze_private_key must not be empty".into(),
            ))
        })?;

        when(
            self.paze_private_key_passphrase.is_default_or_empty(),
            || {
                Err(ApplicationError::InvalidConfigurationValueError(
                    "paze_private_key_passphrase must not be empty".into(),
                ))
            },
        )
    }
}

impl super::settings::GooglePayDecryptConfig {
    pub fn validate(&self) -> Result<(), ApplicationError> {
        use common_utils::fp_utils::when;

        when(
            self.google_pay_root_signing_keys.is_default_or_empty(),
            || {
                Err(ApplicationError::InvalidConfigurationValueError(
                    "google_pay_root_signing_keys must not be empty".into(),
                ))
            },
        )?;

        // The private key, gateway id and common merchant id together describe Hyperswitch's
        // registered Google Pay gateway: the key decrypts the token, the id derives the
        // `gateway:<id>` recipient it was signed against, and the common merchant id is sent to
        // the SDK for INTERNAL_GATEWAY merchants that do not supply one of their own. Either all
        // of them are configured or none is, otherwise the INTERNAL_GATEWAY flow raises a payment
        // sheet whose token cannot be decrypted.
        let internal_gateway_fields = [
            (
                "google_pay_private_key",
                self.google_pay_private_key.is_none(),
            ),
            (
                "google_pay_gateway_id",
                self.google_pay_gateway_id.is_none(),
            ),
            (
                "google_pay_common_merchant_id",
                self.google_pay_common_merchant_id.is_none(),
            ),
        ];
        let missing_fields = internal_gateway_fields
            .iter()
            .filter_map(|(field, is_missing)| is_missing.then_some(*field))
            .collect::<Vec<_>>();

        when(
            !missing_fields.is_empty() && missing_fields.len() != internal_gateway_fields.len(),
            || {
                Err(ApplicationError::InvalidConfigurationValueError(format!(
                    "google_pay_private_key, google_pay_gateway_id and \
                     google_pay_common_merchant_id must either all be set or all be unset; \
                     missing: {}",
                    missing_fields.join(", ")
                )))
            },
        )?;

        when(
            self.google_pay_gateway_id
                .as_ref()
                .is_some_and(|gateway_id| gateway_id.trim().is_empty()),
            || {
                Err(ApplicationError::InvalidConfigurationValueError(
                    "google_pay_gateway_id must not be empty".into(),
                ))
            },
        )
    }
}

impl super::settings::KeyManagerConfig {
    pub fn validate(&self) -> Result<(), ApplicationError> {
        use common_utils::fp_utils::when;

        #[cfg(feature = "keymanager_mtls")]
        when(
            self.enabled && (self.ca.is_default_or_empty() || self.cert.is_default_or_empty()),
            || {
                Err(ApplicationError::InvalidConfigurationValueError(
                    "Invalid CA or Certificate for Keymanager.".into(),
                ))
            },
        )?;

        when(self.enabled && self.url.is_default_or_empty(), || {
            Err(ApplicationError::InvalidConfigurationValueError(
                "Invalid URL for Keymanager".into(),
            ))
        })
    }
}

impl super::settings::Platform {
    pub fn validate(&self) -> Result<(), ApplicationError> {
        use common_utils::fp_utils::when;

        when(!self.enabled && self.allow_connected_merchants, || {
            Err(ApplicationError::InvalidConfigurationValueError(
                "platform.allow_connected_merchants cannot be true when platform.enabled is false"
                    .into(),
            ))
        })
    }
}

impl super::settings::OpenRouter {
    pub fn validate(&self) -> Result<(), ApplicationError> {
        use common_utils::fp_utils::when;

        when(
            (self.dynamic_routing_enabled || self.static_routing_enabled)
                && self.url.is_default_or_empty(),
            || {
                Err(ApplicationError::InvalidConfigurationValueError(
                    "OpenRouter base URL must not be empty when it is enabled".into(),
                ))
            },
        )
    }
}

impl super::settings::SageSettings {
    pub fn validate(&self) -> Result<(), ApplicationError> {
        use common_utils::fp_utils::when;

        when(self.enabled && self.base_url.trim().is_empty(), || {
            Err(ApplicationError::InvalidConfigurationValueError(
                "sage.base_url must be set if sage.enabled is true".into(),
            ))
        })?;
        when(self.enabled && self.mint_path.trim().is_empty(), || {
            Err(ApplicationError::InvalidConfigurationValueError(
                "sage.mint_path must be set if sage.enabled is true".into(),
            ))
        })?;
        when(
            self.enabled && self.infra_key.peek().trim().is_empty(),
            || {
                Err(ApplicationError::InvalidConfigurationValueError(
                    "sage.infra_key must be set if sage.enabled is true".into(),
                ))
            },
        )
    }
}

impl super::settings::AccountUpdaterConfig {
    pub fn validate(&self) -> Result<(), ApplicationError> {
        match self {
            Self::Juspay(juspay) => juspay.validate(),
        }
    }
}

impl super::settings::JuspayAccountUpdaterConfig {
    pub fn validate(&self) -> Result<(), ApplicationError> {
        use common_utils::fp_utils::when;

        when(!self.base_url.path().ends_with('/'), || {
            Err(ApplicationError::InvalidConfigurationValueError(
                "account_updater.juspay.base_url must end with a trailing slash".into(),
            ))
        })?;

        let required = [
            ("api_key", self.api_key.peek().as_str()),
            ("merchant_id", self.merchant_id.as_str()),
            (
                "euler_encryption_public_key",
                self.euler_encryption_public_key.peek().as_str(),
            ),
            (
                "au_decryption_pvt_key",
                self.au_decryption_pvt_key.peek().as_str(),
            ),
            ("card_sync_key_id", self.card_sync_key_id.as_str()),
        ];

        for (field, value) in required {
            when(value.trim().is_empty(), || {
                Err(ApplicationError::InvalidConfigurationValueError(format!(
                    "account_updater.juspay.{field} must not be empty"
                )))
            })?;
        }

        when(self.supported_card_networks.is_empty(), || {
            Err(ApplicationError::InvalidConfigurationValueError(
                "account_updater.juspay.supported_card_networks must list at least one card network"
                    .into(),
            ))
        })?;

        when(self.refresh_timeout_in_secs == 0, || {
            Err(ApplicationError::InvalidConfigurationValueError(
                "account_updater.juspay.refresh_timeout_in_secs must be greater than zero".into(),
            ))
        })?;

        Ok(())
    }
}