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

fix(events): mask header values for outgoing webhook events (#14046)

Kashifa17a23c4c4c9
diff --git a/crates/hyperswitch_domain_models/src/business_profile.rs b/crates/hyperswitch_domain_models/src/business_profile.rs
index 429b413fe0..974c504406 100644
--- a/crates/hyperswitch_domain_models/src/business_profile.rs
+++ b/crates/hyperswitch_domain_models/src/business_profile.rs
@@ -1,10 +1,10 @@
-use std::collections::HashSet;
+use std::collections::{HashMap, HashSet};
use common_enums::enums as api_enums;
use common_types::{domain::AcquirerConfig, primitive_wrappers};
use common_utils::{
crypto::{OptionalEncryptableName, OptionalEncryptableValue},
- errors::{CustomResult, ValidationError},
+ errors::{CustomResult, ParsingError, ValidationError},
ext_traits::{OptionExt, ValueExt},
pii,
};
@@ -16,10 +16,13 @@ use diesel_models::business_profile::{
SurchargeConnectorDetails, WebhookDetails,
};
use error_stack::ResultExt;
-use hyperswitch_masking::ExposeInterface;
+use hyperswitch_masking::{ExposeInterface, Secret};
use router_env::logger;
-use crate::{errors::api_error_response, merchant_key_store::MerchantKeyStore, payments};
+use crate::{
+ consts::SENSITIVE_WEBHOOK_HEADER_NAMES, errors::api_error_response,
+ merchant_key_store::MerchantKeyStore, payments,
+};
#[cfg(feature = "v1")]
#[derive(Clone, Debug, serde::Serialize, serde::Deserialize)]
pub struct Profile {
@@ -918,6 +921,46 @@ impl From<ProfileDbBuilder> for Profile {
}
impl Profile {
+ pub fn get_outgoing_webhook_headers(
+ &self,
+ ) -> CustomResult<Option<HashMap<String, Secret<String>>>, ParsingError> {
+ self.outgoing_webhook_custom_http_headers
+ .as_ref()
+ .map(|outgoing_webhook_custom_http_headers| {
+ outgoing_webhook_custom_http_headers
+ .clone()
+ .into_inner()
+ .expose()
+ .parse_value::<HashMap<String, Secret<String>>>(
+ "HashMap<String, Secret<String>>",
+ )
+ })
+ .transpose()
+ }
+
+ pub fn get_sensitive_webhook_header_names(&self) -> Option<HashSet<String>> {
+ let custom_http_headers = self
+ .get_outgoing_webhook_headers()
+ .inspect_err(|error| {
+ logger::error!(
+ ?error,
+ "Failed to parse outgoing webhook custom HTTP headers"
+ )
+ })
+ .ok()?;
+
+ Some(
+ custom_http_headers
+ .unwrap_or_default()
+ .into_keys()
+ .map(|header_name| header_name.to_ascii_lowercase())
+ .filter(|header_name| {
+ SENSITIVE_WEBHOOK_HEADER_NAMES.contains(&header_name.as_str())
+ })
+ .collect(),
+ )
+ }
+
pub fn get_is_tax_connector_enabled(&self) -> bool {
let is_tax_connector_enabled = self.is_tax_connector_enabled;
match &self.tax_connector_id {
diff --git a/crates/hyperswitch_domain_models/src/consts.rs b/crates/hyperswitch_domain_models/src/consts.rs
index 49df11976f..8c01d1fff0 100644
--- a/crates/hyperswitch_domain_models/src/consts.rs
+++ b/crates/hyperswitch_domain_models/src/consts.rs
@@ -25,3 +25,6 @@ pub static ROUTING_ENABLED_PAYMENT_METHOD_TYPES: LazyLock<
/// Length of the unique reference ID generated for connector mandate requests
pub const CONNECTOR_MANDATE_REQUEST_REFERENCE_ID_LENGTH: usize = 18;
+
+/// Custom list for masking sensitive webhook headers in the events API.
+pub const SENSITIVE_WEBHOOK_HEADER_NAMES: [&str; 1] = ["authorization"];
diff --git a/crates/router/src/consts.rs b/crates/router/src/consts.rs
index 23bb7b33d0..63d668c3e3 100644
--- a/crates/router/src/consts.rs
+++ b/crates/router/src/consts.rs
@@ -508,6 +508,9 @@ pub mod superposition {
pub const SAVE_WALLET_DECRYPTED_DATA: &str = "vaulting.save_wallet_decrypted_data";
}
+/// The value substituted for sensitive webhook header values in event retrieval responses.
+pub const REDACTED_HEADER_VALUE: &str = "*** ***";
+
#[cfg(test)]
mod tests {
#[test]
diff --git a/crates/router/src/core/webhooks/utils.rs b/crates/router/src/core/webhooks/utils.rs
index c488278ef2..2aec9d27c2 100644
--- a/crates/router/src/core/webhooks/utils.rs
+++ b/crates/router/src/core/webhooks/utils.rs
@@ -1,3 +1,5 @@
+#[cfg(feature = "olap")]
+use std::collections::HashSet;
use std::marker::PhantomData;
use base64::Engine;
@@ -14,10 +16,14 @@ use hyperswitch_domain_models::{
router_response_types::{VerifyWebhookSourceResponseData, VerifyWebhookStatus},
};
use hyperswitch_interfaces::webhooks::IncomingWebhook;
+#[cfg(feature = "olap")]
+use hyperswitch_masking::Secret;
use redis_interface as redis;
use router_env::tracing;
use super::{types as webhook_types, MERCHANT_ID};
+#[cfg(feature = "olap")]
+use crate::consts::REDACTED_HEADER_VALUE;
use crate::{
core::{
configs::dimension_state,
@@ -557,3 +563,25 @@ where
.attach_printable("Error while deleting redis key"),
}
}
+
+/// `Secret` does not mask values under ordinary serde serialization, and header sensitivity
+/// depends on the header *name*, which the value wrapper cannot observe. Values are therefore
+/// replaced before the webhook content is returned in an API response.
+///
+/// Header names are compared case-insensitively.
+/// `None` means the sensitive header names could not be determined, in which case every value is
+/// redacted rather than risking exposure.
+#[cfg(feature = "olap")]
+pub fn redact_header_values(
+ headers: &mut [(String, Secret<String>)],
+ sensitive_header_names: Option<&HashSet<String>>,
+) {
+ for (header_name, header_value) in headers {
+ let is_sensitive = sensitive_header_names
+ .is_none_or(|names| names.contains(header_name.to_ascii_lowercase().as_str()));
+
+ if is_sensitive {
+ *header_value = Secret::new(REDACTED_HEADER_VALUE.to_string());
+ }
+ }
+}
diff --git a/crates/router/src/core/webhooks/webhook_events.rs b/crates/router/src/core/webhooks/webhook_events.rs
index 4cac099158..2aa32f174a 100644
--- a/crates/router/src/core/webhooks/webhook_events.rs
+++ b/crates/router/src/core/webhooks/webhook_events.rs
@@ -292,16 +292,38 @@ pub async fn list_delivery_attempts(
))
.attach_printable("No delivery attempts found with the specified `initial_attempt_id`")
} else {
+ // All events in a delivery attempt chain share an `initial_attempt_id`, and therefore the
+ // same business profile, so a single lookup covers the whole list.
+ let sensitive_header_names = match events
+ .first()
+ .and_then(|event| event.business_profile_id.clone())
+ {
+ Some(business_profile_id) => store
+ .find_business_profile_by_profile_id(&key_store, &business_profile_id)
+ .await
+ .inspect_err(|error| {
+ router_env::logger::error!(
+ ?error,
+ "Failed to find business profile for webhook event delivery attempts, \
+ redacting all webhook header values"
+ )
+ })
+ .ok()
+ .and_then(|business_profile| business_profile.get_sensitive_webhook_header_names()),
+ None => None,
+ };
+
Ok(ApplicationResponse::Json(
events
.into_iter()
.map(|event| {
- api::webhook_events::EventRetrieveResponse::try_from(
+ api::webhook_events::EventRetrieveResponse::foreign_try_from((
domain::EventWithDeliverySuccessSource {
event,
source: domain::DeliverySuccessSource::ListDeliveryAttempts,
},
- )
+ sensitive_header_names.as_ref(),
+ ))
})
.collect::<Result<Vec<_>, _>>()?,
))
@@ -417,6 +439,8 @@ pub async fn retry_delivery_attempt(
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to parse webhook event request information")?;
+ let sensitive_header_names = business_profile.get_sensitive_webhook_header_names();
+
Box::pin(super::outgoing::trigger_webhook_and_raise_event(
state.clone(),
business_profile,
@@ -438,12 +462,13 @@ pub async fn retry_delivery_attempt(
.to_not_found_response(errors::ApiErrorResponse::EventNotFound)?;
Ok(ApplicationResponse::Json(
- api::webhook_events::EventRetrieveResponse::try_from(
+ api::webhook_events::EventRetrieveResponse::foreign_try_from((
domain::EventWithDeliverySuccessSource {
event: updated_event,
source: domain::DeliverySuccessSource::ListDeliveryAttempts,
},
- )?,
+ sensitive_header_names.as_ref(),
+ ))?,
))
}
diff --git a/crates/router/src/types/transformers.rs b/crates/router/src/types/transformers.rs
index 9c4cfd1c85..de0a55c2ba 100644
--- a/crates/router/src/types/transformers.rs
+++ b/crates/router/src/types/transformers.rs
@@ -20,6 +20,8 @@ use hyperswitch_domain_models::{mandates, payments::payment_intent::CustomerData
use hyperswitch_masking::{ExposeInterface, PeekInterface, Secret};
use super::domain;
+#[cfg(feature = "olap")]
+use crate::core::webhooks::utils::redact_header_values;
#[cfg(feature = "v2")]
use crate::db::storage::revenue_recovery_redis_operation;
use crate::{
@@ -2241,12 +2243,20 @@ impl TryFrom<domain::EventWithDeliverySuccessSource>
}
#[cfg(feature = "olap")]
-impl TryFrom<domain::EventWithDeliverySuccessSource>
- for api_models::webhook_events::EventRetrieveResponse
+impl
+ ForeignTryFrom<(
+ domain::EventWithDeliverySuccessSource,
+ Option<&std::collections::HashSet<String>>,
+ )> for api_models::webhook_events::EventRetrieveResponse
{
type Error = error_stack::Report<errors::ApiErrorResponse>;
- fn try_from(value: domain::EventWithDeliverySuccessSource) -> Result<Self, Self::Error> {
+ fn foreign_try_from(
+ (value, sensitive_header_names): (
+ domain::EventWithDeliverySuccessSource,
+ Option<&std::collections::HashSet<String>>,
+ ),
+ ) -> Result<Self, Self::Error> {
use crate::utils::OptionExt;
let item = value.event.clone();
@@ -2256,7 +2266,7 @@ impl TryFrom<domain::EventWithDeliverySuccessSource>
// We cannot retrieve events with only some of these fields populated.
let event_information = api_models::webhook_events::EventListItemResponse::try_from(value)?;
- let request = item
+ let mut request: api_models::webhook_events::OutgoingWebhookRequestContent = item
.request
.get_required_value("request")
.change_context(errors::ApiErrorResponse::InternalServerError)?
@@ -2264,7 +2274,7 @@ impl TryFrom<domain::EventWithDeliverySuccessSource>
.parse_struct("OutgoingWebhookRequestContent")
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to parse webhook event request information")?;
- let response = item
+ let mut response: api_models::webhook_events::OutgoingWebhookResponseContent = item
.response
.get_required_value("response")
.change_context(errors::ApiErrorResponse::InternalServerError)?
@@ -2273,6 +2283,13 @@ impl TryFrom<domain::EventWithDeliverySuccessSource>
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to parse webhook event response information")?;
+ // The persisted event retains the original header values, which webhook retries reuse.
+ // The keys are masked only in the response
+ redact_header_values(&mut request.headers, sensitive_header_names);
+ if let Some(headers) = response.headers.as_mut() {
+ redact_header_values(headers, sensitive_header_names);
+ }
+
Ok(Self {
event_information,
request,