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): reject non-mTLS webhooks for connectors that require mTLS (#14787)

Anurag Thakure797b36a1af2
diff --git a/config/config.example.toml b/config/config.example.toml
index 70cb334aa8..64f69d4735 100644
--- a/config/config.example.toml
+++ b/config/config.example.toml
@@ -312,6 +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_webhooks]
+# mtls_verified_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.
[merchant_id_auth]
diff --git a/config/superposition_seed.toml b/config/superposition_seed.toml
index 8ae7b92fb9..e71a22fcc2 100644
--- a/config/superposition_seed.toml
+++ b/config/superposition_seed.toml
@@ -14,6 +14,7 @@
# graph (path → deja_dimension).
[default-configs]
+"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" }
"offer_engine.credential_source" = { value = "none", schema = { type = "string", enum = [
diff --git a/crates/hyperswitch_connectors/src/connectors/santander.rs b/crates/hyperswitch_connectors/src/connectors/santander.rs
index 9d96318873..e69cfc4f27 100644
--- a/crates/hyperswitch_connectors/src/connectors/santander.rs
+++ b/crates/hyperswitch_connectors/src/connectors/santander.rs
@@ -2114,8 +2114,8 @@ impl webhooks::IncomingWebhook for Santander {
_connector_account_details: crypto::Encryptable<Secret<serde_json::Value>>,
_connector_name: &str,
) -> CustomResult<bool, errors::ConnectorError> {
- // Source verification for Santander is MTLS which is handled at the transport layer. No additional verification is needed here in application side
- Ok(true)
+ // The router establishes source verification only after successful mTLS validation.
+ Ok(false)
}
fn get_webhook_object_reference_id(
@@ -2470,6 +2470,10 @@ static SANTANDER_CONNECTOR_INFO: ConnectorInfo = ConnectorInfo {
static SANTANDER_SUPPORTED_WEBHOOK_FLOWS: [enums::EventClass; 0] = [];
impl ConnectorSpecifications for Santander {
+ fn is_webhook_mtls_required(&self) -> bool {
+ true
+ }
+
fn is_payment_recurrence_operation_needed(
&self,
setup_future_usage: Option<common_enums::FutureUsage>,
diff --git a/crates/hyperswitch_connectors/src/connectors/worldpayxml.rs b/crates/hyperswitch_connectors/src/connectors/worldpayxml.rs
index effbd3cddb..8a0233c6e5 100644
--- a/crates/hyperswitch_connectors/src/connectors/worldpayxml.rs
+++ b/crates/hyperswitch_connectors/src/connectors/worldpayxml.rs
@@ -1388,7 +1388,7 @@ impl webhooks::IncomingWebhook for Worldpayxml {
>,
_connector_label: &str,
) -> CustomResult<bool, errors::ConnectorError> {
- // Bypass Source Verification since it is done via MTLS
+ // The router establishes source verification only after successful mTLS validation.
Ok(false)
}
@@ -1573,6 +1573,10 @@ static WORLDPAYXML_SUPPORTED_WEBHOOK_FLOWS: &[common_enums::EventClass] = &[
];
impl ConnectorSpecifications for Worldpayxml {
+ fn is_webhook_mtls_required(&self) -> bool {
+ true
+ }
+
fn get_connector_about(&self) -> Option<&'static ConnectorInfo> {
Some(&WORLDPAYXML_CONNECTOR_INFO)
}
diff --git a/crates/hyperswitch_interfaces/src/api.rs b/crates/hyperswitch_interfaces/src/api.rs
index e4ad2b9da3..cfb45bd46d 100644
--- a/crates/hyperswitch_interfaces/src/api.rs
+++ b/crates/hyperswitch_interfaces/src/api.rs
@@ -522,6 +522,11 @@ pub trait ConnectorSpecifications {
None
}
+ /// Whether incoming webhooks must be received over a verified mTLS connection.
+ fn is_webhook_mtls_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 beb26f8776..eb8f2b8856 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_mtls_required(&self) -> bool {
+ match self {
+ Self::Old(connector) => connector.is_webhook_mtls_required(),
+ Self::New(connector) => connector.is_webhook_mtls_required(),
+ }
+ }
+
fn is_balance_check_flow_required(&self, current_flow: CurrentFlowInfo) -> bool {
match self {
Self::Old(connector) => connector.is_balance_check_flow_required(current_flow),
diff --git a/crates/router/src/configs/secrets_transformers.rs b/crates/router/src/configs/secrets_transformers.rs
index 5ea54e6a61..4c2816d77b 100644
--- a/crates/router/src/configs/secrets_transformers.rs
+++ b/crates/router/src/configs/secrets_transformers.rs
@@ -719,6 +719,7 @@ pub(crate) async fn fetch_raw_secrets(
scheduler: conf.scheduler,
jwekey,
webhooks: conf.webhooks,
+ incoming_webhooks: conf.incoming_webhooks,
pm_filters: conf.pm_filters,
customer_acceptance_support: conf.customer_acceptance_support,
payout_method_filters: conf.payout_method_filters,
diff --git a/crates/router/src/configs/settings.rs b/crates/router/src/configs/settings.rs
index 6647a7ac76..daef280570 100644
--- a/crates/router/src/configs/settings.rs
+++ b/crates/router/src/configs/settings.rs
@@ -110,6 +110,7 @@ pub struct Settings<S: SecretState> {
pub drainer: DrainerSettings,
pub jwekey: SecretStateContainer<Jwekey, S>,
pub webhooks: WebhooksSettings,
+ pub incoming_webhooks: IncomingWebhooksSettings,
pub pm_filters: ConnectorFilters,
pub customer_acceptance_support: CustomerAcceptanceSupportConfig,
pub bank_config: BankRedirectConfig,
@@ -1326,6 +1327,12 @@ pub struct WebhooksSettings {
pub redis_lock_expiry_seconds: u32,
}
+#[derive(Debug, Clone, Default, Deserialize)]
+#[serde(default)]
+pub struct IncomingWebhooksSettings {
+ pub mtls_verified_header: Option<String>,
+}
+
#[derive(Debug, Clone, Deserialize, Default)]
#[serde(default)]
pub struct WebhookIgnoreErrorSettings {
diff --git a/crates/router/src/consts.rs b/crates/router/src/consts.rs
index f26343ad96..aa5757d633 100644
--- a/crates/router/src/consts.rs
+++ b/crates/router/src/consts.rs
@@ -548,6 +548,9 @@ 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";
+ /// Whether incoming webhook mTLS verification is enabled, defaults to `false`.
+ pub const INCOMING_WEBHOOK_MTLS_VERIFICATION_ENABLED: &str =
+ "incoming_webhooks.mtls_verification_enabled";
/// Whether unverified webhook rate limiting is enabled, defaults to `false`
pub const UNVERIFIED_WEBHOOK_RATE_LIMIT_ENABLED: &str =
"webhooks.unverified_webhook_rate_limit_enabled";
diff --git a/crates/router/src/core/configs/dimension_config.rs b/crates/router/src/core/configs/dimension_config.rs
index 134eed154e..ef57c8ff10 100644
--- a/crates/router/src/core/configs/dimension_config.rs
+++ b/crates/router/src/core/configs/dimension_config.rs
@@ -978,6 +978,18 @@ impl DatabaseBackedConfig for IncomingWebhookDisabledEvents {
}
}
+config! {
+ superposition_key = INCOMING_WEBHOOK_MTLS_VERIFICATION_ENABLED,
+ output = bool,
+ default = false,
+ requires = dimension_state::DimensionsWithConnector,
+ targeting_key = id_type::MerchantId
+}
+
+impl DatabaseBackedConfig for IncomingWebhookMtlsVerificationEnabled {
+ const KEY: &'static str = "incoming_webhook_mtls_verification_enabled";
+}
+
config! {
superposition_key = UNVERIFIED_WEBHOOK_RATE_LIMIT_ENABLED,
output = bool,
diff --git a/crates/router/src/core/configs/dimension_state.rs b/crates/router/src/core/configs/dimension_state.rs
index 11db723f37..d16c8ad683 100644
--- a/crates/router/src/core/configs/dimension_state.rs
+++ b/crates/router/src/core/configs/dimension_state.rs
@@ -648,6 +648,17 @@ pub type DimensionsGlobal = Dimensions<
NoPaymentMethodType,
>;
+pub type DimensionsWithConnector = Dimensions<
+ NoProviderMerchantId,
+ NoProcessorMerchantId,
+ NoOrgId,
+ NoProfileId,
+ HasConnector,
+ NoPayoutRetryType,
+ NoWebhookEvent,
+ NoPaymentMethodType,
+>;
+
pub type DimensionsWithProviderMerchantId = Dimensions<
HasProviderMerchantId,
NoProcessorMerchantId,
diff --git a/crates/router/src/core/metrics.rs b/crates/router/src/core/metrics.rs
index c2d9c2e55e..3b1f4e66ce 100644
--- a/crates/router/src/core/metrics.rs
+++ b/crates/router/src/core/metrics.rs
@@ -50,6 +50,7 @@ counter_metric!(WEBHOOK_UNVERIFIED_RATE_LIMIT_CHECKED_COUNT, GLOBAL_METER);
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_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 7602d2a9e2..33d665cfae 100644
--- a/crates/router/src/core/webhooks.rs
+++ b/crates/router/src/core/webhooks.rs
@@ -12,6 +12,7 @@ mod outgoing;
mod outgoing_v2;
#[cfg(all(feature = "revenue_recovery", feature = "v2"))]
pub mod recovery_incoming;
+mod source_verification;
pub mod types;
pub mod unverified_rate_limit;
pub mod utils;
diff --git a/crates/router/src/core/webhooks/incoming.rs b/crates/router/src/core/webhooks/incoming.rs
index a28cc2c1a2..0c9696cdec 100644
--- a/crates/router/src/core/webhooks/incoming.rs
+++ b/crates/router/src/core/webhooks/incoming.rs
@@ -38,7 +38,7 @@ use hyperswitch_masking::{ExposeInterface, PeekInterface, Secret};
use router_env::{instrument, tracing, tracing::Instrument};
use unified_connector_service_client::payments as payments_grpc;
-use super::{types, MERCHANT_ID};
+use super::{source_verification::IncomingWebhookVerifier, types, MERCHANT_ID};
use crate::{
consts,
core::{
@@ -217,12 +217,16 @@ async fn incoming_webhooks_core<W: types::OutgoingWebhookType>(
.await?;
// Each arm resolves its path (UAS vs Direct/UCS) and returns a
- // `WebhookOutcome` plus the connector/name used for acks, errors, and
- // logging. Downstream filter interception and business-logic dispatch are
- // identical for both and run once after the match.
- let (connector, connector_name, outcome) = match three_ds_execution_path {
+ // `WebhookOutcome`, the network verification decision, and the connector/name
+ // used for acks, errors, and logging. Downstream filter interception and
+ // business-logic dispatch are identical for both and run once after the match.
+ let (connector, connector_name, network_verification, outcome) = match three_ds_execution_path {
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)
+ .await?;
+
let (uas_connector, _) =
get_connector_by_connector_name(&state, UNIFIED_AUTHENTICATION_SERVICE, None)?;
@@ -236,11 +240,15 @@ async fn incoming_webhooks_core<W: types::OutgoingWebhookType>(
))
.await;
- (uas_connector, connector_name, outcome)
+ (uas_connector, connector_name, network_verification, outcome)
}
ThreeDsProcessingMode::Direct(ref mca_data) => {
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)
+ .await?;
+
let mca_ref = mca_data.merchant_connector_account.as_ref();
let connector_enum = Connector::from_str(&connector_name)
@@ -335,7 +343,7 @@ async fn incoming_webhooks_core<W: types::OutgoingWebhookType>(
let outcome =
super::gateway::execute_incoming_webhook_gateway(&ctx, &request_details).await;
- (connector, connector_name, outcome)
+ (connector, connector_name, network_verification, outcome)
}
};
@@ -381,6 +389,7 @@ async fn incoming_webhooks_core<W: types::OutgoingWebhookType>(
merchant_connector_account: processed_mca,
ack_response,
}) => {
+ let source_verified = network_verification.resolve_source_verified(source_verified);
// Reconstruct request_details with the decoded body when available
// (Direct and UAS paths), so downstream connector methods that parse
// request_details.body (get_dispute_details, get_webhook_mandate_details,
diff --git a/crates/router/src/core/webhooks/incoming_v2.rs b/crates/router/src/core/webhooks/incoming_v2.rs
index d0fb069bf6..bd1fab891d 100644
--- a/crates/router/src/core/webhooks/incoming_v2.rs
+++ b/crates/router/src/core/webhooks/incoming_v2.rs
@@ -15,7 +15,7 @@ use hyperswitch_interfaces::webhooks::{IncomingWebhookRequestDetails, WebhookRes
use hyperswitch_masking::Secret;
use router_env::{instrument, tracing};
-use super::{types, utils, MERCHANT_ID};
+use super::{source_verification::IncomingWebhookVerifier, types, utils, MERCHANT_ID};
#[cfg(feature = "revenue_recovery")]
use crate::core::webhooks::recovery_incoming;
use crate::{
@@ -141,6 +141,10 @@ async fn incoming_webhooks_core<W: types::OutgoingWebhookType>(
)
.await?;
+ let network_verification = IncomingWebhookVerifier::new(&state.conf.incoming_webhooks)
+ .verify(&state, &connector, request_details.headers)
+ .await?;
+
let decoded_body = connector
.decode_webhook_body(
&request_details,
@@ -282,6 +286,7 @@ async fn incoming_webhooks_core<W: types::OutgoingWebhookType>(
.attach_printable("There was an issue in incoming webhook source verification")?
};
+ let source_verified = network_verification.resolve_source_verified(source_verified);
logger::info!(source_verified=?source_verified);
if source_verified {
diff --git a/crates/router/src/core/webhooks/source_verification.rs b/crates/router/src/core/webhooks/source_verification.rs
new file mode 100644
index 0000000000..20c5bb83ab
--- /dev/null
+++ b/crates/router/src/core/webhooks/source_verification.rs
@@ -0,0 +1,313 @@
+//! Source verification for incoming webhooks.
+
+use actix_web::http::header::HeaderMap;
+use common_enums::connector_enums::Connector;
+use error_stack::{report, ResultExt};
+use hyperswitch_interfaces::api::{ConnectorCommon, ConnectorSpecifications};
+use router_env::logger;
+
+use crate::{
+ configs::settings::IncomingWebhooksSettings,
+ core::{
+ configs::dimension_state,
+ errors::{self, RouterResult},
+ metrics,
+ },
+ routes::SessionState,
+ services::connector_integration_interface::ConnectorEnum,
+};
+
+/// Verifies incoming webhook sources using connector requirements and deployment settings.
+#[derive(Debug)]
+pub(super) struct IncomingWebhookVerifier<'a> {
+ settings: &'a IncomingWebhooksSettings,
+}
+
+/// The outcome of incoming webhook network verification, such as mTLS or source IP checks.
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub(super) enum NetworkVerification {
+ /// The source passed network verification.
+ Verified,
+ /// Required verification was disabled; the source remains unverified.
+ Skipped,
+ /// The connector does not require network verification.
+ NotRequired,
+}
+
+impl NetworkVerification {
+ /// Use connector source verification only when network verification is not 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,
+ }
+ }
+}
+
+impl<'a> IncomingWebhookVerifier<'a> {
+ pub(super) fn new(settings: &'a IncomingWebhooksSettings) -> Self {
+ Self { settings }
+ }
+
+ /// Run router-managed source verification before processing the webhook.
+ pub(super) async fn verify(
+ &self,
+ state: &SessionState,
+ connector: &ConnectorEnum,
+ request_headers: &HeaderMap,
+ ) -> RouterResult<NetworkVerification> {
+ self.verify_mtls(state, connector, request_headers).await
+ }
+
+ /// Enforce mTLS before processing when enabled in Superposition for the connector.
+ /// Trusted ingress must set the configured header to `true` only on verified mTLS
+ /// endpoints and strip caller-supplied values from all other endpoints.
+ async fn verify_mtls(
+ &self,
+ state: &SessionState,
+ connector: &ConnectorEnum,
+ request_headers: &HeaderMap,
+ ) -> RouterResult<NetworkVerification> {
+ if connector.is_webhook_mtls_required() {
+ let connector_name = connector
+ .id()
+ .parse::<Connector>()
+ .change_context(errors::ApiErrorResponse::IncorrectConnectorNameGiven)?;
+ let enabled = dimension_state::Dimensions::new()
+ .with_connector(connector_name)
+ .get_incoming_webhook_mtls_verification_enabled(
+ state.store.as_ref(),
+ state.superposition_service.as_ref(),
+ None,
+ )
+ .await;
+ if enabled {
+ self.validate_mtls(connector, request_headers)
+ } else {
+ logger::info!(
+ connector = %connector_name,
+ "Skipping incoming webhook mTLS verification because incoming_webhooks.mtls_verification_enabled is disabled"
+ );
+ Ok(NetworkVerification::Skipped)
+ }
+ } else {
+ Ok(NetworkVerification::NotRequired)
+ }
+ }
+
+ /// Validate the header after connector requirements and enablement have been checked.
+ fn validate_mtls(
+ &self,
+ connector: &ConnectorEnum,
+ request_headers: &HeaderMap,
+ ) -> RouterResult<NetworkVerification> {
+ let connector_name = connector.id();
+ self.is_mtls_verification_header_present(request_headers)
+ .and_then(|verified| {
+ if !verified {
+ let message = "Incoming webhook mTLS verification failed: the request has missing or invalid verification header";
+ Err(
+ report!(errors::ApiErrorResponse::WebhookAuthenticationFailed)
+ .attach_printable(message),
+ )
+ } else {
+ Ok(NetworkVerification::Verified)
+ }
+ })
+ .inspect_err(|_| {
+ metrics::WEBHOOK_MTLS_VERIFICATION_FAILURE_COUNT.add(
+ 1,
+ router_env::metric_attributes!(("connector", connector_name.to_string())),
+ );
+ })
+ }
+
+ /// Require exactly one configured mTLS verification header with the value `true`.
+ fn is_mtls_verification_header_present(
+ &self,
+ request_headers: &HeaderMap,
+ ) -> RouterResult<bool> {
+ match self
+ .settings
+ .mtls_verified_header
+ .as_deref()
+ .filter(|header_name| !header_name.is_empty())
+ {
+ Some(header_name) => {
+ let mut header_values = request_headers.get_all(header_name);
+ Ok(header_values
+ .next()
+ .is_some_and(|value| value.as_bytes() == b"true")
+ && header_values.next().is_none())
+ }
+ None => Err(
+ report!(errors::ApiErrorResponse::WebhookAuthenticationFailed)
+ .attach_printable("incoming_webhooks.mtls_verified_header is not configured"),
+ ),
+ }
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use actix_web::http::header::{HeaderMap, HeaderName, HeaderValue};
+ use external_services::superposition::Config;
+
+ use super::{IncomingWebhookVerifier, NetworkVerification};
+ use crate::{
+ configs::settings::IncomingWebhooksSettings,
+ core::{configs::dimension_config::IncomingWebhookMtlsVerificationEnabled, errors},
+ services::connector_integration_interface::ConnectorEnum,
+ types::api::ConnectorData,
+ };
+
+ const TEST_MTLS_HEADER: &str = "x-test-mtls-verified";
+
+ fn settings() -> IncomingWebhooksSettings {
+ IncomingWebhooksSettings {
+ mtls_verified_header: Some(TEST_MTLS_HEADER.to_string()),
+ }
+ }
+
+ fn connector(name: &str) -> ConnectorEnum {
+ ConnectorData::convert_connector(name).unwrap()
+ }
+
+ fn headers_with(values: &[&'static str]) -> HeaderMap {
+ let mut request_headers = HeaderMap::new();
+ for value in values {
+ request_headers.append(
+ HeaderName::from_static(TEST_MTLS_HEADER),
+ HeaderValue::from_static(value),
+ );
+ }
+ request_headers
+ }
+
+ #[test]
+ fn mtls_verification_is_disabled_by_default() {
+ assert!(!IncomingWebhookMtlsVerificationEnabled::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));
+ }
+
+ #[test]
+ fn network_verification_establishes_source_verification() {
+ assert!(NetworkVerification::Verified.resolve_source_verified(false));
+ assert!(NetworkVerification::Verified.resolve_source_verified(true));
+ }
+
+ #[test]
+ fn connectors_without_network_verification_use_connector_result() {
+ assert!(NetworkVerification::NotRequired.resolve_source_verified(true));
+ assert!(!NetworkVerification::NotRequired.resolve_source_verified(false));
+ }
+
+ #[test]
+ fn accepts_single_true_value() {
+ assert!(IncomingWebhookVerifier::new(&settings())
+ .is_mtls_verification_header_present(&headers_with(&["true"]))
+ .unwrap());
+ }
+
+ #[test]
+ fn rejects_missing_header() {
+ assert!(!IncomingWebhookVerifier::new(&settings())
+ .is_mtls_verification_header_present(&headers_with(&[]))
+ .unwrap());
+ }
+
+ #[test]
+ fn rejects_other_values() {
+ for value in ["false", "TRUE", "1", "true,true", " true", ""] {
+ assert!(!IncomingWebhookVerifier::new(&settings())
+ .is_mtls_verification_header_present(&headers_with(&[value]))
+ .unwrap());
+ }
+ }
+
+ #[test]
+ fn rejects_repeated_header() {
+ assert!(!IncomingWebhookVerifier::new(&settings())
+ .is_mtls_verification_header_present(&headers_with(&["true", "true"]))
+ .unwrap());
+ }
+
+ #[test]
+ fn rejects_requests_without_verified_mtls() {
+ let settings = settings();
+ let verifier = IncomingWebhookVerifier::new(&settings);
+ for name in ["santander", "worldpayxml"] {
+ let connector = connector(name);
+ let error = verifier
+ .validate_mtls(&connector, &HeaderMap::new())
+ .unwrap_err();
+ assert!(matches!(
+ error.current_context(),
+ errors::ApiErrorResponse::WebhookAuthenticationFailed
+ ));
+ assert!(format!("{error:?}").contains("missing or invalid verification header"));
+ assert_eq!(
+ verifier
+ .validate_mtls(&connector, &headers_with(&["true"]))
+ .unwrap(),
+ NetworkVerification::Verified
+ );
+ }
+ }
+
+ #[test]
+ fn uses_only_the_configured_header() {
+ let settings = IncomingWebhooksSettings {
+ mtls_verified_header: Some("x-custom-mtls-verified".to_string()),
+ };
+ let verifier = IncomingWebhookVerifier::new(&settings);
+ let connector = connector("santander");
+ assert!(verifier
+ .validate_mtls(&connector, &headers_with(&["true"]))
+ .is_err());
+ let mut request_headers = HeaderMap::new();
+ request_headers.append(
+ HeaderName::from_static("x-custom-mtls-verified"),
+ HeaderValue::from_static("true"),
+ );
+ assert!(verifier.validate_mtls(&connector, &request_headers).is_ok());
+ request_headers.append(
+ HeaderName::from_static("x-custom-mtls-verified"),
+ HeaderValue::from_static("true"),
+ );
+ assert!(verifier
+ .validate_mtls(&connector, &request_headers)
+ .is_err());
+ }
+
+ #[test]
+ fn deserializes_default_and_custom_header_names() {
+ let settings: IncomingWebhooksSettings =
+ serde_json::from_value(serde_json::json!({})).unwrap();
+ assert!(settings.mtls_verified_header.is_none());
+ let connector = connector("worldpayxml");
+ let error = IncomingWebhookVerifier::new(&settings)
+ .validate_mtls(&connector, &headers_with(&["true"]))
+ .unwrap_err();
+ assert!(format!("{error:?}")
+ .contains("incoming_webhooks.mtls_verified_header is not configured"));
+ let settings: IncomingWebhooksSettings = serde_json::from_value(serde_json::json!({
+ "mtls_verified_header": "X-Custom-Mtls-Verified"
+ }))
+ .unwrap();
+ let mut request_headers = HeaderMap::new();
+ request_headers.insert(
+ HeaderName::from_static("x-custom-mtls-verified"),
+ HeaderValue::from_static("true"),
+ );
+ assert!(IncomingWebhookVerifier::new(&settings)
+ .validate_mtls(&connector, &request_headers)
+ .is_ok());
+ }
+}