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(router): validate urls (#14506)
Ayush Anand9689f477bddc
diff --git a/Cargo.lock b/Cargo.lockindex 1a74ca8aae..d0e45c25cd 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -2211,6 +2211,7 @@ dependencies = ["hex","http 0.2.12","hyperswitch_masking",+ "ip_network","md5","nanoid","nutype",@@ -5275,6 +5276,12 @@ dependencies = ["libc",]+[[package]]+name = "ip_network"+version = "0.4.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "aa2f047c0a98b2f299aa5d6d7088443570faae494e9ae1305e48be000c9e0eb1"+[[package]]name = "ipnet"version = "2.9.0"diff --git a/api-reference/v1/openapi_spec_v1.json b/api-reference/v1/openapi_spec_v1.jsonindex c646a9e548..6bb75250a7 100644--- a/api-reference/v1/openapi_spec_v1.json+++ b/api-reference/v1/openapi_spec_v1.json@@ -28121,7 +28121,7 @@"webhook_details": {"allOf": [{- "$ref": "#/components/schemas/WebhookDetails"+ "$ref": "#/components/schemas/WebhookDetailsRequest"}],"nullable": true@@ -28597,7 +28597,7 @@"webhook_details": {"allOf": [{- "$ref": "#/components/schemas/WebhookDetails"+ "$ref": "#/components/schemas/WebhookDetailsResponse"}],"nullable": true@@ -28749,7 +28749,7 @@"webhook_details": {"allOf": [{- "$ref": "#/components/schemas/WebhookDetails"+ "$ref": "#/components/schemas/WebhookDetailsRequest"}],"nullable": true@@ -43002,7 +43002,7 @@"webhook_details": {"allOf": [{- "$ref": "#/components/schemas/WebhookDetails"+ "$ref": "#/components/schemas/WebhookDetailsRequest"}],"nullable": true@@ -43381,7 +43381,7 @@"webhook_details": {"allOf": [{- "$ref": "#/components/schemas/WebhookDetails"+ "$ref": "#/components/schemas/WebhookDetailsResponse"}],"nullable": true@@ -50928,7 +50928,134 @@"manual_retry"]},- "WebhookDetails": {+ "WebhookDetailsRequest": {+ "type": "object",+ "required": [+ "payment_statuses_enabled",+ "refund_statuses_enabled"+ ],+ "properties": {+ "webhook_version": {+ "type": "string",+ "description": "The version for Webhook",+ "example": "1.0.2",+ "nullable": true,+ "maxLength": 255+ },+ "webhook_username": {+ "type": "string",+ "description": "The user name for Webhook login",+ "example": "ekart_retail",+ "nullable": true,+ "maxLength": 255+ },+ "webhook_password": {+ "type": "string",+ "description": "The password for Webhook login",+ "example": "ekart@123",+ "nullable": true,+ "maxLength": 255+ },+ "webhook_url": {+ "type": "string",+ "description": "The HTTP or HTTPS webhook URL. DNS must resolve to public addresses. Must not be empty;\nomit this field entirely to leave an existing stored webhook URL unchanged.",+ "example": "https://www.ekart.com/webhooks",+ "nullable": true,+ "minLength": 1+ },+ "payment_created_enabled": {+ "type": "boolean",+ "description": "If this property is true, a webhook message is posted whenever a new payment is created",+ "example": true,+ "nullable": true+ },+ "payment_succeeded_enabled": {+ "type": "boolean",+ "description": "If this property is true, a webhook message is posted whenever a payment is successful",+ "example": true,+ "nullable": true+ },+ "payment_failed_enabled": {+ "type": "boolean",+ "description": "If this property is true, a webhook message is posted whenever a payment fails",+ "example": true,+ "nullable": true+ },+ "payment_statuses_enabled": {+ "type": "array",+ "items": {+ "$ref": "#/components/schemas/IntentStatus"+ },+ "description": "List of payment statuses that triggers a webhook for payment intents",+ "example": [+ "succeeded",+ "failed",+ "partially_captured",+ "requires_merchant_action"+ ]+ },+ "refund_statuses_enabled": {+ "type": "array",+ "items": {+ "$ref": "#/components/schemas/RefundStatus"+ },+ "description": "List of refund statuses that triggers a webhook for refunds",+ "example": [+ "success",+ "failure"+ ]+ },+ "payout_statuses_enabled": {+ "type": "array",+ "items": {+ "$ref": "#/components/schemas/PayoutStatus"+ },+ "description": "List of payout statuses that triggers a webhook for payouts",+ "example": [+ "success",+ "failed"+ ],+ "nullable": true+ },+ "dispute_statuses_enabled": {+ "type": "array",+ "items": {+ "$ref": "#/components/schemas/DisputeStatus"+ },+ "description": "List of dispute statuses that trigger outgoing webhooks for disputes",+ "example": [+ "dispute_opened",+ "dispute_won"+ ],+ "nullable": true+ },+ "mandate_statuses_enabled": {+ "type": "array",+ "items": {+ "$ref": "#/components/schemas/MandateStatus"+ },+ "description": "List of mandate statuses that trigger outgoing webhooks for mandates",+ "example": [+ "active",+ "inactive"+ ],+ "nullable": true+ },+ "invoice_statuses_enabled": {+ "type": "array",+ "items": {+ "$ref": "#/components/schemas/InvoiceStatus"+ },+ "description": "List of invoice statuses that trigger outgoing webhooks for subscriptions",+ "example": [+ "invoice_paid"+ ],+ "nullable": true+ }+ },+ "additionalProperties": false+ },+ "WebhookDetailsResponse": {"type": "object","required": ["payment_statuses_enabled",@@ -50959,7 +51086,7 @@"webhook_url": {"type": "string","description": "The url for the webhook endpoint",- "example": "www.ekart.com/webhooks",+ "example": "https://www.ekart.com/webhooks","nullable": true},"payment_created_enabled": {diff --git a/api-reference/v2/openapi_spec_v2.json b/api-reference/v2/openapi_spec_v2.jsonindex 582c192899..bf4878b1fa 100644--- a/api-reference/v2/openapi_spec_v2.json+++ b/api-reference/v2/openapi_spec_v2.json@@ -29619,7 +29619,7 @@"webhook_details": {"allOf": [{- "$ref": "#/components/schemas/WebhookDetails"+ "$ref": "#/components/schemas/WebhookDetailsRequest"}],"nullable": true@@ -29924,7 +29924,7 @@"webhook_details": {"allOf": [{- "$ref": "#/components/schemas/WebhookDetails"+ "$ref": "#/components/schemas/WebhookDetailsResponse"}],"nullable": true@@ -30412,8 +30412,9 @@},"destination_url": {"type": "string",- "description": "The destination URL where the request needs to be forwarded",- "example": "https://api.example.com/endpoint"+ "description": "The non-empty HTTP or HTTPS destination URL. Configured proxy bypass hosts are rejected.\nIP literals must be publicly routable.",+ "example": "https://api.example.com/endpoint",+ "minLength": 1},"headers": {"type": "object",@@ -36679,7 +36680,134 @@"manual_retry"]},- "WebhookDetails": {+ "WebhookDetailsRequest": {+ "type": "object",+ "required": [+ "payment_statuses_enabled",+ "refund_statuses_enabled"+ ],+ "properties": {+ "webhook_version": {+ "type": "string",+ "description": "The version for Webhook",+ "example": "1.0.2",+ "nullable": true,+ "maxLength": 255+ },+ "webhook_username": {+ "type": "string",+ "description": "The user name for Webhook login",+ "example": "ekart_retail",+ "nullable": true,+ "maxLength": 255+ },+ "webhook_password": {+ "type": "string",+ "description": "The password for Webhook login",+ "example": "ekart@123",+ "nullable": true,+ "maxLength": 255+ },+ "webhook_url": {+ "type": "string",+ "description": "The HTTP or HTTPS webhook URL. DNS must resolve to public addresses. Must not be empty;\nomit this field entirely to leave an existing stored webhook URL unchanged.",+ "example": "https://www.ekart.com/webhooks",+ "nullable": true,+ "minLength": 1+ },+ "payment_created_enabled": {+ "type": "boolean",+ "description": "If this property is true, a webhook message is posted whenever a new payment is created",+ "example": true,+ "nullable": true+ },+ "payment_succeeded_enabled": {+ "type": "boolean",+ "description": "If this property is true, a webhook message is posted whenever a payment is successful",+ "example": true,+ "nullable": true+ },+ "payment_failed_enabled": {+ "type": "boolean",+ "description": "If this property is true, a webhook message is posted whenever a payment fails",+ "example": true,+ "nullable": true+ },+ "payment_statuses_enabled": {+ "type": "array",+ "items": {+ "$ref": "#/components/schemas/IntentStatus"+ },+ "description": "List of payment statuses that triggers a webhook for payment intents",+ "example": [+ "succeeded",+ "failed",+ "partially_captured",+ "requires_merchant_action"+ ]+ },+ "refund_statuses_enabled": {+ "type": "array",+ "items": {+ "$ref": "#/components/schemas/RefundStatus"+ },+ "description": "List of refund statuses that triggers a webhook for refunds",+ "example": [+ "success",+ "failure"+ ]+ },+ "payout_statuses_enabled": {+ "type": "array",+ "items": {+ "$ref": "#/components/schemas/PayoutStatus"+ },+ "description": "List of payout statuses that triggers a webhook for payouts",+ "example": [+ "success",+ "failed"+ ],+ "nullable": true+ },+ "dispute_statuses_enabled": {+ "type": "array",+ "items": {+ "$ref": "#/components/schemas/DisputeStatus"+ },+ "description": "List of dispute statuses that trigger outgoing webhooks for disputes",+ "example": [+ "dispute_opened",+ "dispute_won"+ ],+ "nullable": true+ },+ "mandate_statuses_enabled": {+ "type": "array",+ "items": {+ "$ref": "#/components/schemas/MandateStatus"+ },+ "description": "List of mandate statuses that trigger outgoing webhooks for mandates",+ "example": [+ "active",+ "inactive"+ ],+ "nullable": true+ },+ "invoice_statuses_enabled": {+ "type": "array",+ "items": {+ "$ref": "#/components/schemas/InvoiceStatus"+ },+ "description": "List of invoice statuses that trigger outgoing webhooks for subscriptions",+ "example": [+ "invoice_paid"+ ],+ "nullable": true+ }+ },+ "additionalProperties": false+ },+ "WebhookDetailsResponse": {"type": "object","required": ["payment_statuses_enabled",@@ -36710,7 +36838,7 @@"webhook_url": {"type": "string","description": "The url for the webhook endpoint",- "example": "www.ekart.com/webhooks",+ "example": "https://www.ekart.com/webhooks","nullable": true},"payment_created_enabled": {diff --git a/crates/api_models/src/admin.rs b/crates/api_models/src/admin.rsindex 64515dfbf1..0069c653d9 100644--- a/crates/api_models/src/admin.rs+++ b/crates/api_models/src/admin.rs@@ -10,9 +10,7 @@ use common_utils::{};#[cfg(feature = "v1")]use common_utils::{crypto::OptionalEncryptableName, ext_traits::ValueExt};-#[cfg(feature = "v2")]-use hyperswitch_masking::ExposeInterface;-use hyperswitch_masking::{PeekInterface, Secret};+use hyperswitch_masking::{ExposeInterface, PeekInterface, Secret};use serde::{Deserialize, Serialize};use smithy::SmithyModel;use utoipa::ToSchema;@@ -50,7 +48,7 @@ pub struct MerchantAccountCreate {pub return_url: Option<url::Url>,/// Webhook related details- pub webhook_details: Option<WebhookDetails>,+ pub webhook_details: Option<WebhookDetailsRequest>,/// The routing algorithm to be used for routing payments to desired connectors#[serde(skip)]@@ -452,7 +450,7 @@ pub struct MerchantAccountUpdate {pub return_url: Option<url::Url>,/// Webhook related details- pub webhook_details: Option<WebhookDetails>,+ pub webhook_details: Option<WebhookDetailsRequest>,/// The routing algorithm to be used for routing payments to desired connectors#[serde(skip)]@@ -675,7 +673,7 @@ pub struct MerchantAccountResponse {pub merchant_details: Option<Encryptable<pii::SecretSerdeValue>>,/// Webhook related details- pub webhook_details: Option<WebhookDetails>,+ pub webhook_details: Option<WebhookDetailsResponse>,/// The routing algorithm to be used to process the incoming request from merchant to outgoing payment processor or payment method. The default is 'Custom'#[serde(skip)]@@ -867,7 +865,65 @@ pub struct PrimaryBusinessDetails {#[derive(Clone, Debug, Deserialize, ToSchema, Serialize)]#[serde(deny_unknown_fields)]-pub struct WebhookDetails {+pub struct WebhookDetailsRequest {+ ///The version for Webhook+ #[schema(max_length = 255, max_length = 255, example = "1.0.2")]+ pub webhook_version: Option<String>,++ ///The user name for Webhook login+ #[schema(max_length = 255, max_length = 255, example = "ekart_retail")]+ pub webhook_username: Option<String>,++ ///The password for Webhook login+ #[schema(value_type = Option<String>, max_length = 255, example = "ekart@123")]+ pub webhook_password: Option<Secret<String>>,++ /// The HTTP or HTTPS webhook URL. DNS must resolve to public addresses. Must not be empty;+ /// omit this field entirely to leave an existing stored webhook URL unchanged.+ #[schema(value_type = Option<String>, min_length = 1, example = "https://www.ekart.com/webhooks")]+ pub webhook_url: Option<Secret<common_utils::outbound_url::SafeOutboundUrl>>,++ /// If this property is true, a webhook message is posted whenever a new payment is created+ #[schema(example = true)]+ pub payment_created_enabled: Option<bool>,++ /// If this property is true, a webhook message is posted whenever a payment is successful+ #[schema(example = true)]+ pub payment_succeeded_enabled: Option<bool>,++ /// If this property is true, a webhook message is posted whenever a payment fails+ #[schema(example = true)]+ pub payment_failed_enabled: Option<bool>,++ /// List of payment statuses that triggers a webhook for payment intents+ #[schema(value_type = Vec<IntentStatus>, example = json!(["succeeded", "failed", "partially_captured", "requires_merchant_action"]))]+ pub payment_statuses_enabled: Option<HashSet<api_enums::IntentStatus>>,++ /// List of refund statuses that triggers a webhook for refunds+ #[schema(value_type = Vec<RefundStatus>, example = json!(["success", "failure"]))]+ pub refund_statuses_enabled: Option<HashSet<api_enums::RefundStatus>>,++ /// List of payout statuses that triggers a webhook for payouts+ #[cfg(feature = "payouts")]+ #[schema(value_type = Option<Vec<PayoutStatus>>, example = json!(["success", "failed"]))]+ pub payout_statuses_enabled: Option<HashSet<api_enums::PayoutStatus>>,++ /// List of dispute statuses that trigger outgoing webhooks for disputes+ #[schema(value_type = Option<Vec<DisputeStatus>>, example = json!(["dispute_opened", "dispute_won"]))]+ pub dispute_statuses_enabled: Option<HashSet<api_enums::DisputeStatus>>,++ /// List of mandate statuses that trigger outgoing webhooks for mandates+ #[schema(value_type = Option<Vec<MandateStatus>>, example = json!(["active", "inactive"]))]+ pub mandate_statuses_enabled: Option<HashSet<api_enums::MandateStatus>>,++ /// List of invoice statuses that trigger outgoing webhooks for subscriptions+ #[schema(value_type = Option<Vec<InvoiceStatus>>, example = json!(["invoice_paid"]))]+ pub invoice_statuses_enabled: Option<HashSet<api_enums::InvoiceStatus>>,+}++#[derive(Clone, Debug, Deserialize, ToSchema, Serialize)]+#[serde(deny_unknown_fields)]+pub struct WebhookDetailsResponse {///The version for Webhook#[schema(max_length = 255, max_length = 255, example = "1.0.2")]pub webhook_version: Option<String>,@@ -881,7 +937,7 @@ pub struct WebhookDetails {pub webhook_password: Option<Secret<String>>,///The url for the webhook endpoint- #[schema(value_type = Option<String>, example = "www.ekart.com/webhooks")]+ #[schema(value_type = Option<String>, example = "https://www.ekart.com/webhooks")]pub webhook_url: Option<Secret<String>>,/// If this property is true, a webhook message is posted whenever a new payment is created@@ -922,42 +978,30 @@ pub struct WebhookDetails {pub invoice_statuses_enabled: Option<HashSet<api_enums::InvoiceStatus>>,}-impl WebhookDetails {- pub fn merge(self, other: Self) -> Self {+impl From<WebhookDetailsRequest> for WebhookDetailsResponse {+ fn from(item: WebhookDetailsRequest) -> Self {Self {- webhook_version: other.webhook_version.or(self.webhook_version),- webhook_username: other.webhook_username.or(self.webhook_username),- webhook_password: other.webhook_password.or(self.webhook_password),- webhook_url: other.webhook_url.or(self.webhook_url),- payment_created_enabled: other- .payment_created_enabled- .or(self.payment_created_enabled),- payment_succeeded_enabled: other- .payment_succeeded_enabled- .or(self.payment_succeeded_enabled),- payment_failed_enabled: other.payment_failed_enabled.or(self.payment_failed_enabled),- payment_statuses_enabled: other- .payment_statuses_enabled- .or(self.payment_statuses_enabled),- refund_statuses_enabled: other- .refund_statuses_enabled- .or(self.refund_statuses_enabled),+ webhook_version: item.webhook_version,+ webhook_username: item.webhook_username,+ webhook_password: item.webhook_password,+ webhook_url: item+ .webhook_url+ .map(|url| Secret::new(url.expose().get_string_repr().to_owned())),+ payment_created_enabled: item.payment_created_enabled,+ payment_failed_enabled: item.payment_failed_enabled,+ payment_succeeded_enabled: item.payment_succeeded_enabled,+ payment_statuses_enabled: item.payment_statuses_enabled,+ refund_statuses_enabled: item.refund_statuses_enabled,#[cfg(feature = "payouts")]- payout_statuses_enabled: other- .payout_statuses_enabled- .or(self.payout_statuses_enabled),- dispute_statuses_enabled: other- .dispute_statuses_enabled- .or(self.dispute_statuses_enabled),- mandate_statuses_enabled: other- .mandate_statuses_enabled- .or(self.mandate_statuses_enabled),- invoice_statuses_enabled: other- .invoice_statuses_enabled- .or(self.invoice_statuses_enabled),+ payout_statuses_enabled: item.payout_statuses_enabled,+ dispute_statuses_enabled: item.dispute_statuses_enabled,+ mandate_statuses_enabled: item.mandate_statuses_enabled,+ invoice_statuses_enabled: item.invoice_statuses_enabled,}}+}+impl WebhookDetailsRequest {fn validate_statuses<T>(statuses: &HashSet<T>, status_type_name: &str) -> Result<(), String>whereT: strum::IntoEnumIterator + Copy + Eq + std::hash::Hash + std::fmt::Debug,@@ -1007,6 +1051,43 @@ impl WebhookDetails {}}+impl WebhookDetailsResponse {+ pub fn merge(self, other: Self) -> Self {+ Self {+ webhook_version: other.webhook_version.or(self.webhook_version),+ webhook_username: other.webhook_username.or(self.webhook_username),+ webhook_password: other.webhook_password.or(self.webhook_password),+ webhook_url: other.webhook_url.or(self.webhook_url),+ payment_created_enabled: other+ .payment_created_enabled+ .or(self.payment_created_enabled),+ payment_succeeded_enabled: other+ .payment_succeeded_enabled+ .or(self.payment_succeeded_enabled),+ payment_failed_enabled: other.payment_failed_enabled.or(self.payment_failed_enabled),+ payment_statuses_enabled: other+ .payment_statuses_enabled+ .or(self.payment_statuses_enabled),+ refund_statuses_enabled: other+ .refund_statuses_enabled+ .or(self.refund_statuses_enabled),+ #[cfg(feature = "payouts")]+ payout_statuses_enabled: other+ .payout_statuses_enabled+ .or(self.payout_statuses_enabled),+ dispute_statuses_enabled: other+ .dispute_statuses_enabled+ .or(self.dispute_statuses_enabled),+ mandate_statuses_enabled: other+ .mandate_statuses_enabled+ .or(self.mandate_statuses_enabled),+ invoice_statuses_enabled: other+ .invoice_statuses_enabled+ .or(self.invoice_statuses_enabled),+ }+ }+}+#[derive(Debug, Serialize, ToSchema)]pub struct MerchantAccountDeleteResponse {/// The identifier for the Merchant Account@@ -2337,7 +2418,7 @@ pub struct ProfileCreate {pub redirect_to_merchant_with_http_post: Option<bool>,/// Webhook related details- pub webhook_details: Option<WebhookDetails>,+ pub webhook_details: Option<WebhookDetailsRequest>,/// Metadata is useful for storing additional, unstructured information on an object.#[schema(value_type = Option<Object>, example = r#"{ "city": "NY", "unit": "245" }"#)]@@ -2551,7 +2632,7 @@ pub struct ProfileCreate {pub redirect_to_merchant_with_http_post: Option<bool>,/// Webhook related details- pub webhook_details: Option<WebhookDetails>,+ pub webhook_details: Option<WebhookDetailsRequest>,/// Metadata is useful for storing additional, unstructured information on an object.#[schema(value_type = Option<Object>, example = r#"{ "city": "NY", "unit": "245" }"#)]@@ -2720,7 +2801,7 @@ pub struct ProfileResponse {pub redirect_to_merchant_with_http_post: bool,/// Webhook related details- pub webhook_details: Option<WebhookDetails>,+ pub webhook_details: Option<WebhookDetailsResponse>,/// Metadata is useful for storing additional, unstructured information on an object.#[schema(value_type = Option<Object>, example = r#"{ "city": "NY", "unit": "245" }"#)]@@ -2948,7 +3029,7 @@ pub struct ProfileResponse {pub redirect_to_merchant_with_http_post: bool,/// Webhook related details- pub webhook_details: Option<WebhookDetails>,+ pub webhook_details: Option<WebhookDetailsResponse>,/// Metadata is useful for storing additional, unstructured information on an object.#[schema(value_type = Option<Object>, example = r#"{ "city": "NY", "unit": "245" }"#)]@@ -3122,7 +3203,7 @@ pub struct ProfileUpdate {pub redirect_to_merchant_with_http_post: Option<bool>,/// Webhook related details- pub webhook_details: Option<WebhookDetails>,+ pub webhook_details: Option<WebhookDetailsRequest>,/// Metadata is useful for storing additional, unstructured information on an object.#[schema(value_type = Option<Object>, example = r#"{ "city": "NY", "unit": "245" }"#)]@@ -3335,7 +3416,7 @@ pub struct ProfileUpdate {pub redirect_to_merchant_with_http_post: Option<bool>,/// Webhook related details- pub webhook_details: Option<WebhookDetails>,+ pub webhook_details: Option<WebhookDetailsRequest>,/// Metadata is useful for storing additional, unstructured information on an object.#[schema(value_type = Option<Object>, example = r#"{ "city": "NY", "unit": "245" }"#)]@@ -3949,6 +4030,32 @@ pub struct MCACGraphData {mod tests {use super::*;+ #[test]+ fn empty_webhook_url_fails_validation_while_omission_preserves_the_destination() {+ let existing: WebhookDetailsResponse = serde_json::from_value(serde_json::json!({+ "webhook_url": "https://merchant.example.com/hook"+ }))+ .expect("configured webhook");++ assert!(+ serde_json::from_value::<WebhookDetailsRequest>(serde_json::json!({+ "webhook_url": ""+ }))+ .is_err()+ );++ let omitted: WebhookDetailsRequest = serde_json::from_value(serde_json::json!({+ "payment_succeeded_enabled": true+ }))+ .expect("partial webhook update");+ let retained =+ serde_json::to_value(existing.merge(omitted.into())).expect("retained webhook");+ assert_eq!(+ retained.get("webhook_url"),+ Some(&serde_json::json!("https://merchant.example.com/hook"))+ );+ }+#[test]fn test_payment_link_config_request_validation() {// Safe input should validate successfullydiff --git a/crates/api_models/src/proxy.rs b/crates/api_models/src/proxy.rsindex 1be81d95fe..63e2c64a4d 100644--- a/crates/api_models/src/proxy.rs+++ b/crates/api_models/src/proxy.rs@@ -31,9 +31,10 @@ impl Headers {pub struct ProxyRequest {/// The request body that needs to be forwardedpub request_body: Value,- /// The destination URL where the request needs to be forwarded- #[schema(value_type = String, example = "https://api.example.com/endpoint")]- pub destination_url: url::Url,+ /// The non-empty HTTP or HTTPS destination URL. Configured proxy bypass hosts are rejected.+ /// IP literals must be publicly routable.+ #[schema(value_type = String, min_length = 1, example = "https://api.example.com/endpoint")]+ pub destination_url: common_utils::outbound_url::SafeOutboundUrl,/// The headers that need to be forwarded#[schema(value_type = Object, example = r#"{ "key1": "value-1", "key2": "value-2" }"#)]pub headers: Headers,@@ -69,3 +70,26 @@ pub struct ProxyResponse {impl common_utils::events::ApiEventMetric for ProxyRequest {}impl common_utils::events::ApiEventMetric for ProxyResponse {}++#[cfg(test)]+mod tests {+ use super::ProxyRequest;++ #[test]+ fn proxy_destination_cannot_be_empty() {+ let mut request = serde_json::json!({+ "request_body": {},+ "destination_url": "https://merchant.example.com/hook",+ "headers": {},+ "method": "GET",+ "token": "pm_example",+ "token_type": "payment_method_id"+ });+ assert!(serde_json::from_value::<ProxyRequest>(request.clone()).is_ok());+ request+ .as_object_mut()+ .expect("proxy request")+ .insert("destination_url".to_string(), serde_json::json!(""));+ assert!(serde_json::from_value::<ProxyRequest>(request).is_err());+ }+}diff --git a/crates/common_utils/Cargo.toml b/crates/common_utils/Cargo.tomlindex 999f921ff6..0dfea39e5f 100644--- a/crates/common_utils/Cargo.toml+++ b/crates/common_utils/Cargo.toml@@ -38,6 +38,7 @@ futures = { version = "0.3.31", optional = true }globset = "0.4.16"hex = "0.4.3"http = "0.2.12"+ip_network = { version = "0.4.1", default-features = false }md5 = "0.7.0"nanoid = "0.4.0"nutype = { version = "0.4.3", features = ["serde"] }@@ -70,7 +71,7 @@ ammonia = "3.3"# First party cratescommon_enums = { version = "0.1.0", path = "../common_enums" }-hyperswitch_masking = { version = "0.0.1", features = ["diesel", "time"] }+hyperswitch_masking = { version = "0.0.1", features = ["diesel", "serde", "time"] }router_env = { version = "0.1.0", path = "../router_env", features = ["log_extra_implicit_fields", "log_custom_entries_to_extra"], optional = true, default-features = false }[target.'cfg(target_arch = "wasm32")'.dependencies.uuid]diff --git a/crates/common_utils/src/lib.rs b/crates/common_utils/src/lib.rsindex 157bb40c6a..c7f3133221 100644--- a/crates/common_utils/src/lib.rs+++ b/crates/common_utils/src/lib.rs@@ -25,6 +25,7 @@ pub mod macros;#[cfg(feature = "metrics")]pub mod metrics;pub mod new_type;+pub mod outbound_url;pub mod payout_method_utils;pub mod pii;#[allow(missing_docs)] // Todo: add docsdiff --git a/crates/common_utils/src/outbound_url.rs b/crates/common_utils/src/outbound_url.rsnew file mode 100644index 0000000000..85a1014c99--- /dev/null+++ b/crates/common_utils/src/outbound_url.rs@@ -0,0 +1,148 @@+//! Input validation for merchant-controlled URLs routed through the configured egress proxy.++use std::net::IpAddr;++use error_stack::Report;+use url::{Host, Url};++use crate::{+ errors::{CustomResult, ValidationError},+ fp_utils::when,+};++/// Whether the given IP address is publicly routable (not private, loopback, link-local, or a+/// cloud metadata address).+pub fn is_global_ip(address: IpAddr) -> bool {+ // Judge IPv4-mapped IPv6 as IPv4, including private and metadata addresses.+ let address = address.to_canonical();+ ip_network::IpNetwork::from(address).is_global()+}++/// An absolute HTTP or HTTPS URL with a publicly routable IP literal, if supplied.+#[derive(Clone, Debug, PartialEq, Eq, Hash, serde::Serialize)]+#[serde(into = "String")]+pub struct SafeOutboundUrl(Url);++impl SafeOutboundUrl {+ /// Validate an already parsed URL.+ pub fn from_url(url: Url) -> CustomResult<Self, ValidationError> {+ when(!matches!(url.scheme(), "http" | "https"), || {+ Err(Report::new(ValidationError::InvalidValue {+ message: "URL must use HTTP or HTTPS".to_string(),+ }))+ })?;+ let address = match url.host() {+ Some(Host::Ipv4(address)) => Some(IpAddr::V4(address)),+ Some(Host::Ipv6(address)) => Some(IpAddr::V6(address)),+ Some(Host::Domain(_)) => None,+ None => None,+ };+ when(+ address.is_some_and(|address| !is_global_ip(address)),+ || {+ Err(Report::new(ValidationError::InvalidValue {+ message: "URL IP address must be publicly routable".to_string(),+ }))+ },+ )?;+ Ok(Self(url))+ }++ /// The URL's host, for callers that need to branch on literal vs. domain-name destinations+ /// (e.g. to resolve a domain name's DNS records before using it as a destination).+ pub fn host(&self) -> Option<Host<&str>> {+ self.0.host()+ }++ /// Reject a destination that matches the configured egress proxy bypass hosts.+ pub fn validate_proxy_bypass_hosts(+ &self,+ bypass_proxy_hosts: Option<&str>,+ ) -> CustomResult<(), ValidationError> {+ let host = self.0.host();+ let is_blocked = bypass_proxy_hosts+ .unwrap_or_default()+ .split(',')+ .map(str::trim)+ .filter(|entry| !entry.trim_matches('.').is_empty())+ .any(|entry| match host.as_ref() {+ Some(Host::Domain(domain)) => {+ let host = domain.trim_end_matches('.').to_ascii_lowercase();+ let entry = entry.trim_matches('.').to_ascii_lowercase();+ entry == "*"+ || host == entry+ || host+ .strip_suffix(&entry)+ .is_some_and(|prefix| prefix.ends_with('.'))+ }+ Some(Host::Ipv4(address)) => {+ let address = IpAddr::V4(*address);+ entry.parse::<IpAddr>().is_ok_and(|ip| ip == address)+ || ip_network::IpNetwork::from_str_truncate(entry)+ .is_ok_and(|network| network.contains(address))+ }+ Some(Host::Ipv6(address)) => {+ let address = IpAddr::V6(*address);+ entry.parse::<IpAddr>().is_ok_and(|ip| ip == address)+ || ip_network::IpNetwork::from_str_truncate(entry)+ .is_ok_and(|network| network.contains(address))+ }+ None => false,+ });+ when(is_blocked, || {+ Err(Report::new(ValidationError::InvalidValue {+ message: "URL matches a configured proxy bypass host".to_string(),+ }))+ })+ }++ /// Get the normalized URL string.+ pub fn get_string_repr(&self) -> &str {+ self.0.as_str()+ }+}++impl<'de> serde::Deserialize<'de> for SafeOutboundUrl {+ fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>+ where+ D: serde::Deserializer<'de>,+ {+ let url = <Url as serde::Deserialize<'de>>::deserialize(deserializer)?;+ Self::from_url(url).map_err(serde::de::Error::custom)+ }+}++impl From<SafeOutboundUrl> for String {+ fn from(value: SafeOutboundUrl) -> Self {+ value.0.into()+ }+}++impl hyperswitch_masking::SerializableSecret for SafeOutboundUrl {}++#[cfg(test)]+mod tests {+ use super::SafeOutboundUrl;++ #[test]+ fn typed_url_validates_syntax_and_preserves_the_json_string() {+ let url: SafeOutboundUrl =+ serde_json::from_str("\"https://merchant.example.com/hook\"").expect("valid typed URL");+ assert_eq!(url.get_string_repr(), "https://merchant.example.com/hook");+ assert_eq!(+ serde_json::to_string(&url).expect("serialized typed URL"),+ "\"https://merchant.example.com/hook\""+ );+ assert!(+ serde_json::from_str::<SafeOutboundUrl>("\"http://merchant.example.com/hook\"").is_ok()+ );+ for value in [+ "",+ "/hook",+ "file:///etc/passwd",+ "ftp://merchant.example.com/hook",+ ] {+ assert!(serde_json::from_value::<SafeOutboundUrl>(serde_json::json!(value)).is_err());+ }+ }+}diff --git a/crates/external_services/src/http_client.rs b/crates/external_services/src/http_client.rsindex 25196b226c..e57cef9ec2 100644--- a/crates/external_services/src/http_client.rs+++ b/crates/external_services/src/http_client.rs@@ -10,6 +10,8 @@ use router_env::{instrument, logger, tracing};pub mod client;/// metrics modulepub mod metrics;+/// outbound_destination module+pub mod outbound_destination;/// request modulepub mod request;diff --git a/crates/external_services/src/http_client/client.rs b/crates/external_services/src/http_client/client.rsindex 613775f1fd..9e395a8064 100644--- a/crates/external_services/src/http_client/client.rs+++ b/crates/external_services/src/http_client/client.rs@@ -93,8 +93,12 @@ pub fn get_client_builder(.unwrap_or_default(),));- let proxy_exclusion_config =- reqwest::NoProxy::from_string(&proxy_config.bypass_proxy_hosts.clone().unwrap_or_default());+ let proxy_exclusion_config = reqwest::NoProxy::from_string(+ proxy_config+ .bypass_proxy_hosts+ .as_deref()+ .unwrap_or_default(),+ );logger::debug!("Proxy HTTP Proxy -> {:?} and HTTPS Proxy -> {:?}",diff --git a/crates/external_services/src/http_client/outbound_destination.rs b/crates/external_services/src/http_client/outbound_destination.rsnew file mode 100644index 0000000000..3ca40eb6db--- /dev/null+++ b/crates/external_services/src/http_client/outbound_destination.rs@@ -0,0 +1,59 @@+//! DNS-resolution guard for merchant-controlled outbound destinations (webhook URLs, proxy+//! destinations), preventing SSRF via domain names that resolve to non-public addresses.++use std::time::Duration;++use common_utils::{+ errors::{CustomResult, ValidationError},+ fp_utils::when,+ outbound_url::{is_global_ip, SafeOutboundUrl},+};+use error_stack::{Report, ResultExt};+use router_env::logger;+use url::Host;++const DNS_LOOKUP_TIMEOUT: Duration = Duration::from_secs(2);++fn invalid_dns_destination() -> ValidationError {+ ValidationError::InvalidValue {+ message: "URL hostname must resolve to publicly routable IP addresses".to_string(),+ }+}++/// Validate proxy bypass rules and resolve hostnames before using a merchant-supplied URL as an+/// outbound destination.+pub async fn validate_destination(+ url: &SafeOutboundUrl,+ bypass_proxy_hosts: Option<&str>,+) -> CustomResult<(), ValidationError> {+ let outcome: CustomResult<(), ValidationError> = async {+ url.validate_proxy_bypass_hosts(bypass_proxy_hosts)?;++ // IP literals were validated during parsing; only domain names need DNS resolution.+ match url.host() {+ Some(Host::Domain(host)) => {+ let addresses =+ tokio::time::timeout(DNS_LOOKUP_TIMEOUT, tokio::net::lookup_host((host, 0)))+ .await+ .change_context(invalid_dns_destination())?+ .change_context(invalid_dns_destination())?;++ let mut addresses = addresses.peekable();+ let is_blocked = addresses.peek().is_none()+ || addresses.any(|address| !is_global_ip(address.ip()));++ when(is_blocked, || Err(Report::new(invalid_dns_destination())))+ }+ _ => Ok(()),+ }+ }+ .await;++ outcome.inspect_err(|error| {+ logger::warn!(+ destination = url.get_string_repr(),+ ?error,+ "rejected outbound destination"+ );+ })+}diff --git a/crates/openapi/src/openapi.rs b/crates/openapi/src/openapi.rsindex b8cae30347..03b1f35199 100644--- a/crates/openapi/src/openapi.rs+++ b/crates/openapi/src/openapi.rs@@ -973,7 +973,8 @@ Never share your secret api keys. Keep them guarded and secure.api_models::admin::MerchantDetails,api_models::admin::ToggleKVRequest,api_models::admin::ToggleKVResponse,- api_models::admin::WebhookDetails,+ api_models::admin::WebhookDetailsRequest,+ api_models::admin::WebhookDetailsResponse,api_models::api_keys::ApiKeyExpiration,api_models::api_keys::CreateApiKeyRequest,api_models::api_keys::CreateApiKeyResponse,diff --git a/crates/openapi/src/openapi_v2.rs b/crates/openapi/src/openapi_v2.rsindex ba0c2417d1..8e11a8bc8a 100644--- a/crates/openapi/src/openapi_v2.rs+++ b/crates/openapi/src/openapi_v2.rs@@ -864,7 +864,8 @@ Never share your secret api keys. Keep them guarded and secure.api_models::admin::MerchantDetails,api_models::admin::ToggleKVRequest,api_models::admin::ToggleKVResponse,- api_models::admin::WebhookDetails,+ api_models::admin::WebhookDetailsRequest,+ api_models::admin::WebhookDetailsResponse,api_models::api_keys::ApiKeyExpiration,api_models::api_keys::CreateApiKeyRequest,api_models::api_keys::CreateApiKeyResponse,diff --git a/crates/router/src/core/admin.rs b/crates/router/src/core/admin.rsindex 710397f47d..04e3ba9c23 100644--- a/crates/router/src/core/admin.rs+++ b/crates/router/src/core/admin.rs@@ -15,7 +15,7 @@ use diesel_models::payment_method;#[cfg(all(any(feature = "v1", feature = "v2"), feature = "olap"))]use diesel_models::{business_profile::CardTestingGuardConfig, organization::OrganizationBridge};use error_stack::{report, FutureExt, ResultExt};-use external_services::http_client::client;+use external_services::http_client::{client, outbound_destination};use hyperswitch_domain_models::merchant_connector_account::{FromRequestEncryptableMerchantConnectorAccount, UpdateEncryptableMerchantConnectorAccount,};@@ -440,6 +440,22 @@ impl MerchantAccountCreateBridge for api::MerchantAccountCreate {},)?;+ if let Some(url) = self+ .webhook_details+ .as_ref()+ .and_then(|details| details.webhook_url.as_ref())+ .map(|secret| secret.peek())+ {+ outbound_destination::validate_destination(+ url,+ state.conf.proxy.bypass_proxy_hosts.as_deref(),+ )+ .await+ .change_context(errors::ApiErrorResponse::InvalidRequestData {+ message: "webhook_url is not valid".to_string(),+ })?;+ }+let webhook_details = self.webhook_details.clone().map(ForeignInto::foreign_into);let pm_collect_link_config = self.get_pm_link_config_as_value().change_context(@@ -1158,6 +1174,22 @@ impl MerchantAccountUpdateBridge for api::MerchantAccountUpdate {},)?;+ if let Some(url) = self+ .webhook_details+ .as_ref()+ .and_then(|details| details.webhook_url.as_ref())+ .map(|secret| secret.peek())+ {+ outbound_destination::validate_destination(+ url,+ state.conf.proxy.bypass_proxy_hosts.as_deref(),+ )+ .await+ .change_context(errors::ApiErrorResponse::InvalidRequestData {+ message: "webhook_url is not valid".to_string(),+ })?;+ }+let webhook_details = self.webhook_details.map(ForeignInto::foreign_into);let parent_merchant_id = get_parent_merchant(@@ -3534,6 +3566,22 @@ impl ProfileCreateBridge for api::ProfileCreate {let current_time = date_time::now();+ if let Some(url) = self+ .webhook_details+ .as_ref()+ .and_then(|details| details.webhook_url.as_ref())+ .map(|secret| secret.peek())+ {+ outbound_destination::validate_destination(+ url,+ state.conf.proxy.bypass_proxy_hosts.as_deref(),+ )+ .await+ .change_context(errors::ApiErrorResponse::InvalidRequestData {+ message: "webhook_url is not valid".to_string(),+ })?;+ }+let webhook_details = self.webhook_details.map(ForeignInto::foreign_into);let payment_response_hash_key = self@@ -3758,6 +3806,22 @@ impl ProfileCreateBridge for api::ProfileCreate {let current_time = date_time::now();+ if let Some(url) = self+ .webhook_details+ .as_ref()+ .and_then(|details| details.webhook_url.as_ref())+ .map(|secret| secret.peek())+ {+ outbound_destination::validate_destination(+ url,+ state.conf.proxy.bypass_proxy_hosts.as_deref(),+ )+ .await+ .change_context(errors::ApiErrorResponse::InvalidRequestData {+ message: "webhook_url is not valid".to_string(),+ })?;+ }+let webhook_details = self.webhook_details.map(ForeignInto::foreign_into);let payment_response_hash_key = self@@ -4101,13 +4165,31 @@ impl ProfileUpdateBridge for api::ProfileUpdate {helpers::validate_intent_fulfillment_expiry(intent_fulfillment_expiry)?;}+ if let Some(url) = self+ .webhook_details+ .as_ref()+ .and_then(|details| details.webhook_url.as_ref())+ .map(|secret| secret.peek())+ {+ outbound_destination::validate_destination(+ url,+ state.conf.proxy.bypass_proxy_hosts.as_deref(),+ )+ .await+ .change_context(errors::ApiErrorResponse::InvalidRequestData {+ message: "webhook_url is not valid".to_string(),+ })?;+ }+let webhook_details = self.webhook_details.map(|webhook_details| {+ let webhook_details =+ api_models::admin::WebhookDetailsResponse::from(webhook_details);let existing_webhook_details = business_profile.webhook_details.clone()- .map(|wh| api_models::admin::WebhookDetails::foreign_from(wh.clone()));+ .map(api_models::admin::WebhookDetailsResponse::foreign_from);match existing_webhook_details {Some(existing_details) => existing_details.merge(webhook_details),@@ -4343,6 +4425,22 @@ impl ProfileUpdateBridge for api::ProfileUpdate {helpers::validate_session_expiry(session_expiry.to_owned())?;}+ if let Some(url) = self+ .webhook_details+ .as_ref()+ .and_then(|details| details.webhook_url.as_ref())+ .map(|secret| secret.peek())+ {+ outbound_destination::validate_destination(+ url,+ state.conf.proxy.bypass_proxy_hosts.as_deref(),+ )+ .await+ .change_context(errors::ApiErrorResponse::InvalidRequestData {+ message: "webhook_url is not valid".to_string(),+ })?;+ }+let webhook_details = self.webhook_details.map(ForeignInto::foreign_into);let payment_link_config = selfdiff --git a/crates/router/src/core/proxy.rs b/crates/router/src/core/proxy.rsindex fcc2ffc9a2..967bf4860c 100644--- a/crates/router/src/core/proxy.rs+++ b/crates/router/src/core/proxy.rs@@ -7,6 +7,7 @@ use common_utils::{request::{self, RequestBuilder},};use error_stack::ResultExt;+use external_services::http_client::outbound_destination;use hyperswitch_interfaces::types::Response;use serde_json::Value;@@ -15,6 +16,15 @@ pub async fn proxy_core(platform: domain::Platform,req: proxy_api_models::ProxyRequest,) -> RouterResponse<proxy_api_models::ProxyResponse> {+ outbound_destination::validate_destination(+ &req.destination_url,+ state.conf.proxy.bypass_proxy_hosts.as_deref(),+ )+ .await+ .change_context(errors::ApiErrorResponse::InvalidRequestData {+ message: "destination_url is not valid".to_string(),+ })?;+let req_wrapper = utils::ProxyRequestWrapper(req.clone());let proxy_record = req_wrapper.get_proxy_record(&state, platform.get_provider())diff --git a/crates/router/src/core/proxy/utils.rs b/crates/router/src/core/proxy/utils.rsindex bff7a5e2a7..b966681f8d 100644--- a/crates/router/src/core/proxy/utils.rs+++ b/crates/router/src/core/proxy/utils.rs@@ -169,7 +169,7 @@ impl ProxyRequestWrapper {}pub fn get_destination_url(&self) -> &str {- self.0.destination_url.as_str()+ self.0.destination_url.get_string_repr()}pub fn get_method(&self) -> common_utils::request::Method {diff --git a/crates/router/src/types/api/admin.rs b/crates/router/src/types/api/admin.rsindex db702656e7..bd7ed24850 100644--- a/crates/router/src/types/api/admin.rs+++ b/crates/router/src/types/api/admin.rs@@ -9,7 +9,7 @@ pub use api_models::{MerchantConnectorDeleteResponse, MerchantConnectorDetails, MerchantConnectorDetailsWrap,MerchantConnectorId, MerchantConnectorResponse, MerchantDetails, MerchantId,PaymentMethodsEnabled, ProfileCreate, ProfileResponse, ProfileUpdate, ToggleAllKVRequest,- ToggleAllKVResponse, ToggleKVRequest, ToggleKVResponse, WebhookDetails,+ ToggleAllKVResponse, ToggleKVRequest, ToggleKVResponse,},organization::{ConvertOrganizationToPlatformRequest, ConvertOrganizationToPlatformResponse,@@ -410,6 +410,22 @@ pub async fn create_profile_from_merchant_account(let current_time = common_utils::date_time::now();+ if let Some(url) = request+ .webhook_details+ .as_ref()+ .and_then(|details| details.webhook_url.as_ref())+ .map(|secret| secret.peek())+ {+ external_services::http_client::outbound_destination::validate_destination(+ url,+ state.conf.proxy.bypass_proxy_hosts.as_deref(),+ )+ .await+ .change_context(errors::ApiErrorResponse::InvalidRequestData {+ message: "webhook_url is not valid".to_string(),+ })?;+ }+let webhook_details = request.webhook_details.map(ForeignInto::foreign_into);let payment_response_hash_key = requestdiff --git a/crates/router/src/types/transformers.rs b/crates/router/src/types/transformers.rsindex 69c7fe8a18..fd0dd26295 100644--- a/crates/router/src/types/transformers.rs+++ b/crates/router/src/types/transformers.rs@@ -2588,10 +2588,18 @@ impl ForeignFrom<diesel_models::business_profile::WalletBlockingConfig>}}-impl ForeignFrom<api_models::admin::WebhookDetails>+impl ForeignFrom<api_models::admin::WebhookDetailsRequest>for diesel_models::business_profile::WebhookDetails{- fn foreign_from(item: api_models::admin::WebhookDetails) -> Self {+ fn foreign_from(item: api_models::admin::WebhookDetailsRequest) -> Self {+ api_models::admin::WebhookDetailsResponse::from(item).foreign_into()+ }+}++impl ForeignFrom<api_models::admin::WebhookDetailsResponse>+ for diesel_models::business_profile::WebhookDetails+{+ fn foreign_from(item: api_models::admin::WebhookDetailsResponse) -> Self {Self {webhook_version: item.webhook_version,webhook_username: item.webhook_username,@@ -2612,7 +2620,7 @@ impl ForeignFrom<api_models::admin::WebhookDetails>}impl ForeignFrom<diesel_models::business_profile::WebhookDetails>- for api_models::admin::WebhookDetails+ for api_models::admin::WebhookDetailsResponse{fn foreign_from(item: diesel_models::business_profile::WebhookDetails) -> Self {Self {