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

feat(webhooks): Introduce IP based whitelisting for incoming webhooks (#14828)

Anurag Thakurf3d1c0d42e9c
diff --git a/Cargo.lock b/Cargo.lock
index 449bdc9888..e03f883822 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -4947,6 +4947,7 @@ dependencies = [
"futures 0.3.31",
"http 0.2.12",
"hyperswitch_masking",
+ "ip_network",
"mime 0.3.17",
"payment_link",
"router_derive",
diff --git a/config/config.example.toml b/config/config.example.toml
index 64f69d4735..af8133962e 100644
--- a/config/config.example.toml
+++ b/config/config.example.toml
@@ -312,9 +312,10 @@ max_age = 365 # Max age of a refund in days.
outgoing_enabled = true
redis_lock_expiry_seconds = 180
-# Incoming webhook mTLS headers are configured in deployment configurations.
+# Incoming webhook verification headers are configured in deployment configurations.
# [incoming_webhooks]
# mtls_verified_header = "<value>"
+# source_ip_header = "<value>"
# Controls whether merchant ID authentication is enabled.
# When enabled, payment endpoints will accept and require a x-merchant-id header in the request.
diff --git a/config/superposition_seed.toml b/config/superposition_seed.toml
index d1ad59a087..594a4e03dd 100644
--- a/config/superposition_seed.toml
+++ b/config/superposition_seed.toml
@@ -14,6 +14,8 @@
# graph (path → deja_dimension).
[default-configs]
+"webhooks.incoming_webhooks_ip_verification_enabled" = { value = false, schema = { type = "boolean" }, description = "Global incoming webhook IP verification toggle. Defaults to false. Applies to connectors requiring IP verification. Disabling skips IP policy lookup and validation and leaves their webhook source unverified. Read without merchant or connector dimensions.", change_reason = "Add runtime kill switch for incoming webhook IP verification" }
+"webhooks.incoming_webhooks_allowed_ip_ranges" = { value = {}, schema = { type = "object", additionalProperties = { type = "array", minItems = 1, items = { type = "string", minLength = 1 } } }, description = "Allowed incoming webhook source IPs/CIDRs by connector. Read without merchant dimensions. Seed before deploying; configure environment-specific lists in Superposition.", change_reason = "Add incoming webhook source IP verification policy" }
"incoming_webhooks.mtls_verification_enabled" = { value = false, schema = { type = "boolean" }, description = "Enable incoming webhook mTLS verification for connectors that require it. Defaults to false; use connector dimension overrides to control individual connectors.", change_reason = "Add runtime toggle for incoming webhook mTLS verification" }
deja_record = { value = false, schema = { type = "boolean" }, description = "Deja per-request recording decision — default SKIP (false). The deja_dimension cohort override (seeded by scripts/seed_superposition.sh) sets this true for the recordable endpoint bucket; /health and other probe traffic fall through to false.", change_reason = "Deja recording sampler" }
"offer_engine.enabled" = { value = false, schema = { type = "boolean" }, description = "Master gate for the Offer Engine integration. When false (default) Offer Engine is never called, regardless of offer_engine.credential_source. Set true (per tenant/env override) to allow Offer Engine calls.", change_reason = "Offer Engine disabled by default; enable via Superposition override" }
diff --git a/crates/hyperswitch_connectors/src/connectors/envoy.rs b/crates/hyperswitch_connectors/src/connectors/envoy.rs
index 3444be6a93..33e324743d 100644
--- a/crates/hyperswitch_connectors/src/connectors/envoy.rs
+++ b/crates/hyperswitch_connectors/src/connectors/envoy.rs
@@ -710,6 +710,10 @@ static ENVOY_CONNECTOR_INFO: ConnectorInfo = ConnectorInfo {
static ENVOY_SUPPORTED_WEBHOOK_FLOWS: [enums::EventClass; 0] = [];
impl ConnectorSpecifications for Envoy {
+ fn is_webhook_ip_verification_required(&self) -> bool {
+ true
+ }
+
fn get_connector_about(&self) -> Option<&'static ConnectorInfo> {
Some(&ENVOY_CONNECTOR_INFO)
}
diff --git a/crates/hyperswitch_domain_models/Cargo.toml b/crates/hyperswitch_domain_models/Cargo.toml
index 775e856854..103b720800 100644
--- a/crates/hyperswitch_domain_models/Cargo.toml
+++ b/crates/hyperswitch_domain_models/Cargo.toml
@@ -40,6 +40,7 @@ base64 = "0.22.1"
error-stack = "0.4.1"
futures = "0.3.31"
http = "0.2.12"
+ip_network = { version = "0.4.1", default-features = false }
mime = "0.3.17"
rustc-hash = "1.1.0"
serde = { version = "1.0.219", features = ["derive"] }
diff --git a/crates/hyperswitch_domain_models/src/lib.rs b/crates/hyperswitch_domain_models/src/lib.rs
index 58489d691a..72143bbd91 100644
--- a/crates/hyperswitch_domain_models/src/lib.rs
+++ b/crates/hyperswitch_domain_models/src/lib.rs
@@ -48,6 +48,7 @@ pub mod transformers;
pub mod type_encryption;
pub mod types;
pub mod vault;
+pub mod webhooks;
#[cfg(not(feature = "payouts"))]
pub trait PayoutAttemptInterface {}
diff --git a/crates/hyperswitch_domain_models/src/webhooks.rs b/crates/hyperswitch_domain_models/src/webhooks.rs
new file mode 100644
index 0000000000..f5e1f7a794
--- /dev/null
+++ b/crates/hyperswitch_domain_models/src/webhooks.rs
@@ -0,0 +1,66 @@
+use std::{net::IpAddr, str::FromStr};
+
+use ip_network::IpNetwork;
+
+/// An incoming webhook source IP or CIDR range, validated during config deserialization.
+#[derive(Debug, serde_with::DeserializeFromStr)]
+pub struct IncomingWebhookIpRange(IpNetwork);
+
+impl FromStr for IncomingWebhookIpRange {
+ type Err = String;
+
+ fn from_str(value: &str) -> Result<Self, Self::Err> {
+ let value = value.trim();
+ value
+ .parse::<IpNetwork>()
+ .or_else(|_| value.parse::<IpAddr>().map(IpNetwork::from))
+ .map(Self)
+ .map_err(|error| {
+ format!("Invalid incoming webhook allowed IP range '{value}': {error}")
+ })
+ }
+}
+
+impl IncomingWebhookIpRange {
+ /// Whether the source IP belongs to this allowed range.
+ pub fn contains(&self, source_ip: IpAddr) -> bool {
+ self.0.contains(source_ip)
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use ip_network::IpNetwork;
+
+ use super::IncomingWebhookIpRange;
+
+ #[test]
+ fn parses_ip_addresses_and_cidr_ranges() {
+ for (value, expected) in [
+ ("198.51.100.10", "198.51.100.10/32"),
+ (" 198.51.100.10 ", "198.51.100.10/32"),
+ ("2001:db8::10", "2001:db8::10/128"),
+ ("195.35.90.0/25", "195.35.90.0/25"),
+ ("2001:db8::/64", "2001:db8::/64"),
+ ] {
+ let range = value.parse::<IncomingWebhookIpRange>().unwrap();
+ assert_eq!(range.0, expected.parse::<IpNetwork>().unwrap());
+ }
+ }
+
+ #[test]
+ fn rejects_invalid_ips_and_cidr_ranges() {
+ for value in [
+ "invalid",
+ "198.51.100.10:46532",
+ "198.51.100.10/33",
+ "198.51.100.10/24",
+ "2001:db8::1/64",
+ ] {
+ assert!(
+ value.parse::<IncomingWebhookIpRange>().is_err(),
+ "accepted {value}"
+ );
+ }
+ }
+}
diff --git a/crates/hyperswitch_interfaces/src/api.rs b/crates/hyperswitch_interfaces/src/api.rs
index cfb45bd46d..46b7974210 100644
--- a/crates/hyperswitch_interfaces/src/api.rs
+++ b/crates/hyperswitch_interfaces/src/api.rs
@@ -527,6 +527,11 @@ pub trait ConnectorSpecifications {
false
}
+ /// Whether incoming webhook source IPs must be checked against allowed IP ranges.
+ fn is_webhook_ip_verification_required(&self) -> bool {
+ false
+ }
+
/// About the connector
fn get_connector_about(&self) -> Option<&'static ConnectorInfo> {
None
diff --git a/crates/hyperswitch_interfaces/src/connector_integration_interface.rs b/crates/hyperswitch_interfaces/src/connector_integration_interface.rs
index eb8f2b8856..08ec02280a 100644
--- a/crates/hyperswitch_interfaces/src/connector_integration_interface.rs
+++ b/crates/hyperswitch_interfaces/src/connector_integration_interface.rs
@@ -580,6 +580,13 @@ impl ConnectorValidation for ConnectorEnum {
}
}
impl ConnectorSpecifications for ConnectorEnum {
+ fn is_webhook_ip_verification_required(&self) -> bool {
+ match self {
+ Self::Old(connector) => connector.is_webhook_ip_verification_required(),
+ Self::New(connector) => connector.is_webhook_ip_verification_required(),
+ }
+ }
+
fn is_webhook_mtls_required(&self) -> bool {
match self {
Self::Old(connector) => connector.is_webhook_mtls_required(),
diff --git a/crates/router/src/configs/settings.rs b/crates/router/src/configs/settings.rs
index a93c042c5b..0eafba1374 100644
--- a/crates/router/src/configs/settings.rs
+++ b/crates/router/src/configs/settings.rs
@@ -1331,6 +1331,7 @@ pub struct WebhooksSettings {
#[serde(default)]
pub struct IncomingWebhooksSettings {
pub mtls_verified_header: Option<String>,
+ pub source_ip_header: Option<String>,
}
#[derive(Debug, Clone, Deserialize, Default)]
diff --git a/crates/router/src/consts.rs b/crates/router/src/consts.rs
index 537ad0c99a..b3390ecada 100644
--- a/crates/router/src/consts.rs
+++ b/crates/router/src/consts.rs
@@ -551,6 +551,12 @@ pub mod superposition {
pub const THREEDS_ROUTING_REGION_UAS: &str = "routing.threeds_routing_region_uas";
/// disabled webhook events configuration key per merchant and connector
pub const INCOMING_WEBHOOK_DISABLED_EVENTS: &str = "webhooks.incoming_webhook_disabled_events";
+ /// Allowed incoming webhook source IPs/CIDRs, keyed by connector.
+ pub const INCOMING_WEBHOOK_ALLOWED_IP_RANGES: &str =
+ "webhooks.incoming_webhooks_allowed_ip_ranges";
+ /// Global incoming webhook IP verification kill switch, defaults to `false`.
+ pub const INCOMING_WEBHOOK_IP_VERIFICATION_ENABLED: &str =
+ "webhooks.incoming_webhooks_ip_verification_enabled";
/// Whether incoming webhook mTLS verification is enabled, defaults to `false`.
pub const INCOMING_WEBHOOK_MTLS_VERIFICATION_ENABLED: &str =
"incoming_webhooks.mtls_verification_enabled";
diff --git a/crates/router/src/core/configs/dimension_config.rs b/crates/router/src/core/configs/dimension_config.rs
index a61900f0fa..4cf24766c0 100644
--- a/crates/router/src/core/configs/dimension_config.rs
+++ b/crates/router/src/core/configs/dimension_config.rs
@@ -1,8 +1,9 @@
-use std::collections::HashSet;
+use std::collections::{HashMap, HashSet};
use api_models::webhooks::IncomingWebhookEvent;
-use common_enums;
+use common_enums::{self, connector_enums};
use external_services::superposition;
+use hyperswitch_domain_models::webhooks::IncomingWebhookIpRange;
use scheduler::consumer::types::process_data::RetryMapping;
use super::{dimension_state, fetch_db_config_for_dimensions, ConfigContext, DatabaseBackedConfig};
@@ -992,6 +993,41 @@ impl DatabaseBackedConfig for IncomingWebhookDisabledEvents {
}
}
+/// Incoming webhook allowed IP ranges, keyed by connector.
+pub type IncomingWebhookIpRangesConfig =
+ HashMap<connector_enums::Connector, Vec<IncomingWebhookIpRange>>;
+
+// An absent config defaults to an empty object; enabled, required checks reject missing ranges.
+config! {
+ superposition_key = INCOMING_WEBHOOK_ALLOWED_IP_RANGES,
+ output = IncomingWebhookIpRangesConfig,
+ default = serde_json::json!({}),
+ object = true,
+ requires = dimension_state::DimensionsGlobal,
+ targeting_key = id_type::MerchantId
+}
+
+impl DatabaseBackedConfig for IncomingWebhookAllowedIpRanges {
+ const KEY: &'static str = "incoming_webhooks_allowed_ip_ranges";
+}
+
+config! {
+ superposition_key = INCOMING_WEBHOOK_IP_VERIFICATION_ENABLED,
+ output = bool,
+ default = false,
+ requires = dimension_state::DimensionsGlobal,
+ targeting_key = id_type::MerchantId
+}
+
+impl DatabaseBackedConfig for IncomingWebhookIpVerificationEnabled {
+ const KEY: &'static str = "incoming_webhook_ip_verification_enabled";
+
+ fn db_key(_dimensions: &impl dimension_state::DimensionsBase) -> Option<String> {
+ // Keep the global kill switch in Superposition without a database fallback.
+ None
+ }
+}
+
config! {
superposition_key = INCOMING_WEBHOOK_MTLS_VERIFICATION_ENABLED,
output = bool,
diff --git a/crates/router/src/core/metrics.rs b/crates/router/src/core/metrics.rs
index 3b1f4e66ce..f9c1a4949c 100644
--- a/crates/router/src/core/metrics.rs
+++ b/crates/router/src/core/metrics.rs
@@ -51,6 +51,7 @@ counter_metric!(WEBHOOK_UNVERIFIED_RATE_LIMITED_COUNT, GLOBAL_METER);
// No. of unverified incoming webhooks let through because the rate limit check failed
counter_metric!(WEBHOOK_UNVERIFIED_RATE_LIMITER_ERROR_COUNT, GLOBAL_METER);
counter_metric!(WEBHOOK_MTLS_VERIFICATION_FAILURE_COUNT, GLOBAL_METER);
+counter_metric!(WEBHOOK_IP_VERIFICATION_FAILURE_COUNT, GLOBAL_METER);
counter_metric!(WEBHOOK_OUTGOING_COUNT, GLOBAL_METER);
counter_metric!(WEBHOOK_OUTGOING_RECEIVED_COUNT, GLOBAL_METER);
counter_metric!(WEBHOOK_OUTGOING_NOT_RECEIVED_COUNT, GLOBAL_METER);
diff --git a/crates/router/src/core/webhooks.rs b/crates/router/src/core/webhooks.rs
index 33d665cfae..2dc08e03c9 100644
--- a/crates/router/src/core/webhooks.rs
+++ b/crates/router/src/core/webhooks.rs
@@ -4,6 +4,7 @@ pub mod gateway;
pub mod incoming;
#[cfg(feature = "v2")]
mod incoming_v2;
+mod ip_verification;
#[cfg(feature = "v1")]
mod network_tokenization_incoming;
#[cfg(feature = "v1")]
diff --git a/crates/router/src/core/webhooks/incoming.rs b/crates/router/src/core/webhooks/incoming.rs
index 6a2ac33be0..ba8ce2a210 100644
--- a/crates/router/src/core/webhooks/incoming.rs
+++ b/crates/router/src/core/webhooks/incoming.rs
@@ -224,7 +224,12 @@ async fn incoming_webhooks_core<W: types::OutgoingWebhookType>(
ThreeDsProcessingMode::UnifiedAuthenticationService(ref mca_data) => {
let connector_name = mca_data.connector_name.clone();
let network_verification = IncomingWebhookVerifier::new(&state.conf.incoming_webhooks)
- .verify(&state, &mca_data.connector, request_details.headers)
+ .verify(
+ &state,
+ &mca_data.connector,
+ &connector_name,
+ request_details.headers,
+ )
.await?;
let (uas_connector, _) =
@@ -246,7 +251,7 @@ async fn incoming_webhooks_core<W: types::OutgoingWebhookType>(
let connector = mca_data.connector.clone();
let connector_name = mca_data.connector_name.clone();
let network_verification = IncomingWebhookVerifier::new(&state.conf.incoming_webhooks)
- .verify(&state, &connector, request_details.headers)
+ .verify(&state, &connector, &connector_name, request_details.headers)
.await?;
let mca_ref = mca_data.merchant_connector_account.as_ref();
diff --git a/crates/router/src/core/webhooks/incoming_v2.rs b/crates/router/src/core/webhooks/incoming_v2.rs
index bd1fab891d..31698176e4 100644
--- a/crates/router/src/core/webhooks/incoming_v2.rs
+++ b/crates/router/src/core/webhooks/incoming_v2.rs
@@ -142,7 +142,7 @@ async fn incoming_webhooks_core<W: types::OutgoingWebhookType>(
.await?;
let network_verification = IncomingWebhookVerifier::new(&state.conf.incoming_webhooks)
- .verify(&state, &connector, request_details.headers)
+ .verify(&state, &connector, &connector_name, request_details.headers)
.await?;
let decoded_body = connector
diff --git a/crates/router/src/core/webhooks/ip_verification.rs b/crates/router/src/core/webhooks/ip_verification.rs
new file mode 100644
index 0000000000..8545af7920
--- /dev/null
+++ b/crates/router/src/core/webhooks/ip_verification.rs
@@ -0,0 +1,242 @@
+//! Incoming webhook source IP validation
+use std::net::IpAddr;
+
+use actix_web::http::header::HeaderMap;
+use common_enums::connector_enums::Connector;
+use common_utils::errors::{CustomResult, ErrorSwitch};
+use error_stack::{report, ResultExt};
+use hyperswitch_domain_models::webhooks::IncomingWebhookIpRange;
+use router_env::logger;
+
+use super::source_verification::VerificationStatus;
+use crate::{
+ core::{configs::dimension_config::IncomingWebhookIpRangesConfig, errors},
+ types::transformers::ForeignTryFrom,
+};
+
+#[derive(Clone, Copy, Debug, PartialEq, Eq, strum::IntoStaticStr, thiserror::Error)]
+#[strum(serialize_all = "snake_case")]
+pub(super) enum VerificationFailure {
+ #[error("Invalid incoming webhook allowed IP ranges config")]
+ InvalidConfig,
+ #[error("Incoming webhook source IP header is not configured")]
+ MissingHeaderConfig,
+ #[error("Incoming webhook source IP header is missing")]
+ MissingHeader,
+ #[error("Incoming webhook source IP header is invalid")]
+ InvalidHeader,
+ #[error("Incoming webhook source IP is outside the allowed ranges")]
+ IpNotAllowed,
+}
+
+impl ErrorSwitch<errors::ApiErrorResponse> for VerificationFailure {
+ fn switch(&self) -> errors::ApiErrorResponse {
+ match self {
+ Self::InvalidConfig => errors::ApiErrorResponse::InternalServerError,
+ Self::MissingHeaderConfig
+ | Self::MissingHeader
+ | Self::InvalidHeader
+ | Self::IpNotAllowed => errors::ApiErrorResponse::WebhookAuthenticationFailed,
+ }
+ }
+}
+
+/// Example Superposition config for `webhooks.incoming_webhooks_allowed_ip_ranges`:
+/// ```json
+/// { "envoy": ["198.51.100.10", "195.35.90.0/25", "2001:db8::/64"] }
+/// ```
+/// Each connector maps to a nonempty list of individual IPs or CIDR ranges.
+/// CIDRs must use the range's base address, with no host bits set.
+/// Connectors requiring IP verification must have an entry when verification is enabled.
+pub(super) fn validate_source_ip_against_allowed_ip_ranges(
+ policy: IncomingWebhookIpRangesConfig,
+ connector_name: Connector,
+ request_headers: &HeaderMap,
+ header_name: Option<&str>,
+) -> CustomResult<VerificationStatus, VerificationFailure> {
+ let connector_allowed_ip_ranges = policy
+ .get(&connector_name)
+ .filter(|ranges| !ranges.is_empty())
+ .ok_or_else(|| {
+ logger::error!(
+ connector = %connector_name,
+ "Incoming webhook allowed IP ranges are missing or empty for the connector"
+ );
+ VerificationFailure::InvalidConfig
+ })?;
+ validate_source_ip(connector_allowed_ip_ranges, request_headers, header_name).inspect_err(
+ |reason| {
+ logger::warn!(
+ connector = %connector_name,
+ ?reason,
+ header = ?header_name,
+ header_config = "incoming_webhooks.source_ip_header",
+ "Incoming webhook source IP verification rejected the request"
+ );
+ },
+ )
+}
+
+fn validate_source_ip(
+ allowed_ip_ranges: &[IncomingWebhookIpRange],
+ request_headers: &HeaderMap,
+ header_name: Option<&str>,
+) -> CustomResult<VerificationStatus, VerificationFailure> {
+ let header_name = header_name
+ .filter(|name| !name.is_empty())
+ .ok_or(VerificationFailure::MissingHeaderConfig)?;
+ let mut values = request_headers.get_all(header_name);
+ let value = values.next().ok_or(VerificationFailure::MissingHeader)?;
+ // Only a single header should be present for client IP
+ if values.next().is_some() {
+ logger::warn!(
+ header = header_name,
+ "Incoming webhook has multiple source IP header values"
+ );
+ Err(report!(VerificationFailure::InvalidHeader))
+ } else {
+ let source =
+ IpAddr::foreign_try_from(value).change_context(VerificationFailure::InvalidHeader)?;
+
+ if allowed_ip_ranges
+ .iter()
+ .any(|ip_range| ip_range.contains(source))
+ {
+ Ok(VerificationStatus::Verified)
+ } else {
+ logger::warn!(
+ source_ip = %source,
+ allowed_range_count = allowed_ip_ranges.len(),
+ "Incoming webhook source IP is outside the allowed ranges"
+ );
+ Err(report!(VerificationFailure::IpNotAllowed))
+ }
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use actix_web::http::header::{HeaderMap, HeaderName, HeaderValue};
+ use common_enums::connector_enums::Connector;
+ use common_utils::errors::CustomResult;
+ use error_stack::ResultExt;
+ use serde_json::json;
+
+ use super::{
+ validate_source_ip, validate_source_ip_against_allowed_ip_ranges, VerificationFailure,
+ VerificationStatus,
+ };
+
+ const TEST_SOURCE_IP_HEADER: &str = "x-test-source-ip";
+
+ fn headers_with(values: &[&str]) -> HeaderMap {
+ let mut headers = HeaderMap::new();
+ for value in values {
+ headers.append(
+ HeaderName::from_static(TEST_SOURCE_IP_HEADER),
+ HeaderValue::from_str(value).unwrap(),
+ );
+ }
+ headers
+ }
+
+ fn verify(
+ policy: serde_json::Value,
+ headers: &HeaderMap,
+ ) -> CustomResult<VerificationStatus, VerificationFailure> {
+ validate_source_ip_against_allowed_ip_ranges(
+ serde_json::from_value(policy).change_context(VerificationFailure::InvalidConfig)?,
+ Connector::Envoy,
+ headers,
+ Some(TEST_SOURCE_IP_HEADER),
+ )
+ }
+
+ #[test]
+ fn validates_ips_with_or_without_ports_against_allowed_ranges() {
+ let policy = json!({"envoy": ["198.51.100.10", "195.35.90.0/25", "2001:db8::/64"]});
+ for value in [
+ "198.51.100.10",
+ "198.51.100.10:46532",
+ "195.35.90.127:46532",
+ "2001:db8::10",
+ "[2001:db8::10]:46532",
+ ] {
+ assert_eq!(
+ verify(policy.clone(), &headers_with(&[value])).unwrap(),
+ VerificationStatus::Verified,
+ "rejected {value}"
+ );
+ }
+ for value in ["198.51.100.11", "195.35.90.128:46532", "2001:db8:1::10"] {
+ assert_eq!(
+ *verify(policy.clone(), &headers_with(&[value]))
+ .unwrap_err()
+ .current_context(),
+ VerificationFailure::IpNotAllowed,
+ "accepted {value}"
+ );
+ }
+ }
+
+ #[test]
+ fn rejects_missing_malformed_and_repeated_headers() {
+ let policy = json!({"envoy": ["198.51.100.10"]});
+ assert_eq!(
+ *verify(policy.clone(), &HeaderMap::new())
+ .unwrap_err()
+ .current_context(),
+ VerificationFailure::MissingHeader
+ );
+ for values in [vec!["not-an-ip"], vec!["198.51.100.10", "198.51.100.10"]] {
+ let error = verify(policy.clone(), &headers_with(&values)).unwrap_err();
+ assert_eq!(*error.current_context(), VerificationFailure::InvalidHeader);
+ }
+ }
+
+ #[test]
+ fn rejects_missing_or_empty_connector_ranges() {
+ for policy in [
+ json!({}),
+ json!({"stripe": ["198.51.100.10"]}),
+ json!({"envoy": []}),
+ ] {
+ assert_eq!(
+ *verify(policy.clone(), &headers_with(&["198.51.100.10"]))
+ .unwrap_err()
+ .current_context(),
+ VerificationFailure::InvalidConfig,
+ "accepted {policy}"
+ );
+ }
+ }
+
+ #[test]
+ fn requires_and_uses_only_the_configured_source_ip_header() {
+ let ranges = ["198.51.100.10/32".parse().unwrap()];
+ let mut headers = headers_with(&["198.51.100.10"]);
+ for name in [None, Some("")] {
+ assert_eq!(
+ *validate_source_ip(&ranges, &headers, name)
+ .unwrap_err()
+ .current_context(),
+ VerificationFailure::MissingHeaderConfig
+ );
+ }
+ let custom_header = "x-custom-source-ip";
+ assert_eq!(
+ *validate_source_ip(&ranges, &headers, Some(custom_header))
+ .unwrap_err()
+ .current_context(),
+ VerificationFailure::MissingHeader
+ );
+ headers.insert(
+ HeaderName::from_static(custom_header),
+ HeaderValue::from_static("198.51.100.10"),
+ );
+ assert_eq!(
+ validate_source_ip(&ranges, &headers, Some(custom_header)).unwrap(),
+ VerificationStatus::Verified
+ );
+ }
+}
diff --git a/crates/router/src/core/webhooks/source_verification.rs b/crates/router/src/core/webhooks/source_verification.rs
index 20c5bb83ab..13aceac4cc 100644
--- a/crates/router/src/core/webhooks/source_verification.rs
+++ b/crates/router/src/core/webhooks/source_verification.rs
@@ -2,10 +2,12 @@
use actix_web::http::header::HeaderMap;
use common_enums::connector_enums::Connector;
+use common_utils::errors::ErrorSwitch;
use error_stack::{report, ResultExt};
use hyperswitch_interfaces::api::{ConnectorCommon, ConnectorSpecifications};
use router_env::logger;
+use super::ip_verification::validate_source_ip_against_allowed_ip_ranges;
use crate::{
configs::settings::IncomingWebhooksSettings,
core::{
@@ -23,24 +25,44 @@ pub(super) struct IncomingWebhookVerifier<'a> {
settings: &'a IncomingWebhooksSettings,
}
-/// The outcome of incoming webhook network verification, such as mTLS or source IP checks.
+/// The outcome of an incoming webhook network verification check.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
-pub(super) enum NetworkVerification {
- /// The source passed network verification.
+pub(super) enum VerificationStatus {
+ /// The source passed this check.
Verified,
- /// Required verification was disabled; the source remains unverified.
- Skipped,
- /// The connector does not require network verification.
+ /// The connector requires this check, but runtime config disables it; the source remains unverified.
+ RequiredButDisabled,
+ /// The connector does not require this check.
NotRequired,
}
+impl VerificationStatus {
+ fn is_verified(self) -> bool {
+ self == Self::Verified
+ }
+
+ fn is_required_but_disabled(self) -> bool {
+ self == Self::RequiredButDisabled
+ }
+}
+
+/// Retains each network check's outcome until connector source verification is resolved.
+#[derive(Debug)]
+pub(super) struct NetworkVerification {
+ mtls: VerificationStatus,
+ source_ip: VerificationStatus,
+}
+
impl NetworkVerification {
- /// Use connector source verification only when network verification is not required.
+ /// A required check disabled by config keeps the source unverified even when another check passes.
+ /// Use connector source verification only when no network check is required.
pub(super) fn resolve_source_verified(self, connector_source_verified: bool) -> bool {
- match self {
- Self::Verified => true,
- Self::Skipped => false,
- Self::NotRequired => connector_source_verified,
+ if self.mtls.is_required_but_disabled() || self.source_ip.is_required_but_disabled() {
+ false
+ } else if self.mtls.is_verified() || self.source_ip.is_verified() {
+ true
+ } else {
+ connector_source_verified
}
}
}
@@ -51,13 +73,87 @@ impl<'a> IncomingWebhookVerifier<'a> {
}
/// Run router-managed source verification before processing the webhook.
+ /// Use the resolved connector name for policy lookup; an adapter's ID can differ.
pub(super) async fn verify(
&self,
state: &SessionState,
connector: &ConnectorEnum,
+ connector_name: &str,
request_headers: &HeaderMap,
) -> RouterResult<NetworkVerification> {
- self.verify_mtls(state, connector, request_headers).await
+ Ok(NetworkVerification {
+ mtls: self.verify_mtls(state, connector, request_headers).await?,
+ source_ip: self
+ .verify_source_ip(state, connector, connector_name, request_headers)
+ .await?,
+ })
+ }
+
+ /// Read the incoming webhooks allowed IP ranges config and validate that the IP is allowed for
+ /// this connector.
+ ///
+ /// Only connectors requiring IP verification consult the config.
+ /// The global IP verification toggle defaults to false and bypasses policy lookup when disabled.
+ /// A missing or invalid policy or current connector's IP ranges is a configuration error.
+ /// Malformed entries invalidate the entire policy during deserialization.
+ async fn verify_source_ip(
+ &self,
+ state: &SessionState,
+ connector: &ConnectorEnum,
+ connector_name: &str,
+ request_headers: &HeaderMap,
+ ) -> RouterResult<VerificationStatus> {
+ if connector.is_webhook_ip_verification_required() {
+ let dimensions = dimension_state::Dimensions::new();
+ let enabled = dimensions
+ .get_incoming_webhook_ip_verification_enabled(
+ state.store.as_ref(),
+ state.superposition_service.as_ref(),
+ None,
+ )
+ .await;
+ if enabled {
+ let connector_name = connector_name
+ .parse::<Connector>()
+ .change_context(errors::ApiErrorResponse::IncorrectConnectorNameGiven)?;
+ let policy = dimensions
+ .get_incoming_webhook_allowed_ip_ranges(
+ state.store.as_ref(),
+ state.superposition_service.as_ref(),
+ None,
+ )
+ .await;
+
+ validate_source_ip_against_allowed_ip_ranges(
+ policy,
+ connector_name,
+ request_headers,
+ self.settings.source_ip_header.as_deref(),
+ )
+ .map_err(|error| {
+ let api_error: errors::ApiErrorResponse = error.current_context().switch();
+ let reason: &'static str = (*error.current_context()).into();
+ metrics::WEBHOOK_IP_VERIFICATION_FAILURE_COUNT.add(
+ 1,
+ router_env::metric_attributes!(
+ ("connector", connector_name.to_string()),
+ ("reason", reason)
+ ),
+ );
+ error.change_context(api_error).attach_printable(format!(
+ "Webhook source IP verification failed: {reason}"
+ ))
+ })
+ } else {
+ logger::info!(
+ connector = %connector_name,
+ "Skipping incoming webhook IP verification because webhooks.incoming_webhooks_ip_verification_enabled is disabled"
+ );
+ Ok(VerificationStatus::RequiredButDisabled)
+ }
+ } else {
+ Ok(VerificationStatus::NotRequired)
+ }
}
/// Enforce mTLS before processing when enabled in Superposition for the connector.
@@ -68,7 +164,7 @@ impl<'a> IncomingWebhookVerifier<'a> {
state: &SessionState,
connector: &ConnectorEnum,
request_headers: &HeaderMap,
- ) -> RouterResult<NetworkVerification> {
+ ) -> RouterResult<VerificationStatus> {
if connector.is_webhook_mtls_required() {
let connector_name = connector
.id()
@@ -89,10 +185,10 @@ impl<'a> IncomingWebhookVerifier<'a> {
connector = %connector_name,
"Skipping incoming webhook mTLS verification because incoming_webhooks.mtls_verification_enabled is disabled"
);
- Ok(NetworkVerification::Skipped)
+ Ok(VerificationStatus::RequiredButDisabled)
}
} else {
- Ok(NetworkVerification::NotRequired)
+ Ok(VerificationStatus::NotRequired)
}
}
@@ -101,7 +197,7 @@ impl<'a> IncomingWebhookVerifier<'a> {
&self,
connector: &ConnectorEnum,
request_headers: &HeaderMap,
- ) -> RouterResult<NetworkVerification> {
+ ) -> RouterResult<VerificationStatus> {
let connector_name = connector.id();
self.is_mtls_verification_header_present(request_headers)
.and_then(|verified| {
@@ -112,7 +208,7 @@ impl<'a> IncomingWebhookVerifier<'a> {
.attach_printable(message),
)
} else {
- Ok(NetworkVerification::Verified)
+ Ok(VerificationStatus::Verified)
}
})
.inspect_err(|_| {
@@ -154,10 +250,15 @@ mod tests {
use actix_web::http::header::{HeaderMap, HeaderName, HeaderValue};
use external_services::superposition::Config;
- use super::{IncomingWebhookVerifier, NetworkVerification};
+ use super::{IncomingWebhookVerifier, NetworkVerification, VerificationStatus};
use crate::{
configs::settings::IncomingWebhooksSettings,
- core::{configs::dimension_config::IncomingWebhookMtlsVerificationEnabled, errors},
+ core::{
+ configs::dimension_config::{
+ IncomingWebhookIpVerificationEnabled, IncomingWebhookMtlsVerificationEnabled,
+ },
+ errors,
+ },
services::connector_integration_interface::ConnectorEnum,
types::api::ConnectorData,
};
@@ -167,6 +268,7 @@ mod tests {
fn settings() -> IncomingWebhooksSettings {
IncomingWebhooksSettings {
mtls_verified_header: Some(TEST_MTLS_HEADER.to_string()),
+ ..Default::default()
}
}
@@ -186,26 +288,39 @@ mod tests {
}
#[test]
- fn mtls_verification_is_disabled_by_default() {
- assert!(!IncomingWebhookMtlsVerificationEnabled::default_value());
+ fn ip_verification_is_disabled_by_default() {
+ assert!(!IncomingWebhookIpVerificationEnabled::default_value());
}
#[test]
- fn skipped_network_verification_does_not_trust_connector_result() {
- assert!(!NetworkVerification::Skipped.resolve_source_verified(true));
- assert!(!NetworkVerification::Skipped.resolve_source_verified(false));
+ fn mtls_verification_is_disabled_by_default() {
+ assert!(!IncomingWebhookMtlsVerificationEnabled::default_value());
}
#[test]
- fn network_verification_establishes_source_verification() {
- assert!(NetworkVerification::Verified.resolve_source_verified(false));
- assert!(NetworkVerification::Verified.resolve_source_verified(true));
- }
+ fn resolves_source_verification_from_all_network_checks() {
+ use VerificationStatus::{NotRequired, RequiredButDisabled, Verified};
- #[test]
- fn connectors_without_network_verification_use_connector_result() {
- assert!(NetworkVerification::NotRequired.resolve_source_verified(true));
- assert!(!NetworkVerification::NotRequired.resolve_source_verified(false));
+ for (mtls, source_ip, expected) in [
+ (NotRequired, NotRequired, None),
+ (NotRequired, Verified, Some(true)),
+ (NotRequired, RequiredButDisabled, Some(false)),
+ (Verified, NotRequired, Some(true)),
+ (Verified, Verified, Some(true)),
+ (Verified, RequiredButDisabled, Some(false)),
+ (RequiredButDisabled, NotRequired, Some(false)),
+ (RequiredButDisabled, Verified, Some(false)),
+ (RequiredButDisabled, RequiredButDisabled, Some(false)),
+ ] {
+ for connector_source_verified in [false, true] {
+ let verification = NetworkVerification { mtls, source_ip };
+ assert_eq!(
+ verification.resolve_source_verified(connector_source_verified),
+ expected.unwrap_or(connector_source_verified),
+ "mTLS={mtls:?}, IP={source_ip:?}, connector={connector_source_verified}"
+ );
+ }
+ }
}
#[test]
@@ -256,7 +371,7 @@ mod tests {
verifier
.validate_mtls(&connector, &headers_with(&["true"]))
.unwrap(),
- NetworkVerification::Verified
+ VerificationStatus::Verified
);
}
}
@@ -265,6 +380,7 @@ mod tests {
fn uses_only_the_configured_header() {
let settings = IncomingWebhooksSettings {
mtls_verified_header: Some("x-custom-mtls-verified".to_string()),
+ ..Default::default()
};
let verifier = IncomingWebhookVerifier::new(&settings);
let connector = connector("santander");
diff --git a/crates/router/src/types/transformers.rs b/crates/router/src/types/transformers.rs
index d40160da4f..4e2e549116 100644
--- a/crates/router/src/types/transformers.rs
+++ b/crates/router/src/types/transformers.rs
@@ -1,4 +1,6 @@
-use actix_web::http::header::HeaderMap;
+use std::net::{IpAddr, SocketAddr};
+
+use actix_web::http::header::{HeaderMap, HeaderValue};
use api_models::{
card_issuer as card_issuer_types, cards_info as card_info_types, enums as api_enums,
gsm as gsm_api_types, offer_engine as offer_engine_api, payment_methods,
@@ -79,6 +81,22 @@ where
}
}
+impl ForeignTryFrom<&HeaderValue> for IpAddr {
+ type Error = error_stack::Report<errors::ParsingError>;
+
+ fn foreign_try_from(value: &HeaderValue) -> Result<Self, Self::Error> {
+ let value = value
+ .to_str()
+ .change_context(errors::ParsingError::StructParseFailure("HeaderValue"))
+ .attach_printable("IP address header is not valid UTF-8")?;
+ value
+ .parse::<Self>()
+ .or_else(|_| value.parse::<SocketAddr>().map(|address| address.ip()))
+ .change_context(errors::ParsingError::StructParseFailure("IpAddr"))
+ .attach_printable("Header value is not an IP or socket address")
+ }
+}
+
impl ForeignFrom<api_models::refunds::RefundType> for storage_enums::RefundType {
fn foreign_from(item: api_models::refunds::RefundType) -> Self {
match item {