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(events): add masked json serializer for logging PII values (#2681)

Sampras Lopes13c66df92c5b
diff --git a/crates/api_models/src/admin.rs b/crates/api_models/src/admin.rs
index 45c0d3c658..b1a258e6b2 100644
--- a/crates/api_models/src/admin.rs
+++ b/crates/api_models/src/admin.rs
@@ -14,12 +14,12 @@ use crate::{
payment_methods,
};
-#[derive(Clone, Debug, Deserialize, ToSchema)]
+#[derive(Clone, Debug, Deserialize, ToSchema, Serialize)]
pub struct MerchantAccountListRequest {
pub organization_id: String,
}
-#[derive(Clone, Debug, Deserialize, ToSchema)]
+#[derive(Clone, Debug, Deserialize, ToSchema, Serialize)]
#[serde(deny_unknown_fields)]
pub struct MerchantAccountCreate {
/// The identifier for the Merchant Account
@@ -111,7 +111,7 @@ pub struct MerchantAccountMetadata {
#[serde(flatten)]
pub data: Option<pii::SecretSerdeValue>,
}
-#[derive(Clone, Debug, Deserialize, ToSchema)]
+#[derive(Clone, Debug, Deserialize, ToSchema, Serialize)]
#[serde(deny_unknown_fields)]
pub struct MerchantAccountUpdate {
/// The identifier for the Merchant Account
@@ -1006,7 +1006,7 @@ pub enum PayoutStraightThroughAlgorithm {
Single(api_enums::PayoutConnectors),
}
-#[derive(Clone, Debug, Deserialize, ToSchema, Default)]
+#[derive(Clone, Debug, Deserialize, ToSchema, Default, Serialize)]
#[serde(deny_unknown_fields)]
pub struct BusinessProfileCreate {
/// A short name to identify the business profile
@@ -1127,7 +1127,7 @@ pub struct BusinessProfileResponse {
pub applepay_verified_domains: Option<Vec<String>>,
}
-#[derive(Clone, Debug, Deserialize, ToSchema)]
+#[derive(Clone, Debug, Deserialize, ToSchema, Serialize)]
#[serde(deny_unknown_fields)]
pub struct BusinessProfileUpdate {
/// A short name to identify the business profile
diff --git a/crates/api_models/src/api_keys.rs b/crates/api_models/src/api_keys.rs
index 30f0699693..f0ab403d9c 100644
--- a/crates/api_models/src/api_keys.rs
+++ b/crates/api_models/src/api_keys.rs
@@ -5,7 +5,7 @@ use time::PrimitiveDateTime;
use utoipa::ToSchema;
/// The request body for creating an API Key.
-#[derive(Debug, Deserialize, ToSchema)]
+#[derive(Debug, Deserialize, ToSchema, Serialize)]
#[serde(deny_unknown_fields)]
pub struct CreateApiKeyRequest {
/// A unique name for the API Key to help you identify it.
@@ -111,7 +111,7 @@ pub struct RetrieveApiKeyResponse {
}
/// The request body for updating an API Key.
-#[derive(Debug, Deserialize, ToSchema)]
+#[derive(Debug, Deserialize, ToSchema, Serialize)]
#[serde(deny_unknown_fields)]
pub struct UpdateApiKeyRequest {
/// A unique name for the API Key to help you identify it.
diff --git a/crates/api_models/src/cards_info.rs b/crates/api_models/src/cards_info.rs
index 552f7f54b1..9eda9c7c57 100644
--- a/crates/api_models/src/cards_info.rs
+++ b/crates/api_models/src/cards_info.rs
@@ -8,7 +8,7 @@ pub struct CardsInfoRequestParams {
pub client_secret: Option<String>,
}
-#[derive(serde::Deserialize, Debug)]
+#[derive(serde::Deserialize, Debug, serde::Serialize)]
pub struct CardsInfoRequest {
pub client_secret: Option<String>,
pub card_iin: String,
diff --git a/crates/api_models/src/disputes.rs b/crates/api_models/src/disputes.rs
index 1b04e79227..b8955bb8ff 100644
--- a/crates/api_models/src/disputes.rs
+++ b/crates/api_models/src/disputes.rs
@@ -99,7 +99,7 @@ pub struct DisputeEvidenceBlock {
pub file_metadata_response: files::FileMetadataResponse,
}
-#[derive(Clone, Debug, Deserialize, ToSchema)]
+#[derive(Clone, Debug, Deserialize, ToSchema, Serialize)]
#[serde(deny_unknown_fields)]
pub struct DisputeListConstraints {
/// limit on the number of objects to return
diff --git a/crates/api_models/src/mandates.rs b/crates/api_models/src/mandates.rs
index ca0037db85..035f7adec9 100644
--- a/crates/api_models/src/mandates.rs
+++ b/crates/api_models/src/mandates.rs
@@ -62,7 +62,7 @@ pub struct MandateCardDetails {
pub card_fingerprint: Option<Secret<String>>,
}
-#[derive(Clone, Debug, Deserialize, ToSchema)]
+#[derive(Clone, Debug, Deserialize, ToSchema, Serialize)]
#[serde(deny_unknown_fields)]
pub struct MandateListConstraints {
/// limit on the number of objects to return
diff --git a/crates/api_models/src/payments.rs b/crates/api_models/src/payments.rs
index c0ec959725..f9cb21dae5 100644
--- a/crates/api_models/src/payments.rs
+++ b/crates/api_models/src/payments.rs
@@ -2111,7 +2111,7 @@ pub struct PaymentsResponse {
pub merchant_connector_id: Option<String>,
}
-#[derive(Clone, Debug, serde::Deserialize, ToSchema)]
+#[derive(Clone, Debug, serde::Deserialize, ToSchema, serde::Serialize)]
#[serde(deny_unknown_fields)]
pub struct PaymentListConstraints {
/// The identifier for customer
@@ -2187,7 +2187,7 @@ pub struct PaymentListResponseV2 {
pub data: Vec<PaymentsResponse>,
}
-#[derive(Clone, Debug, serde::Deserialize)]
+#[derive(Clone, Debug, serde::Deserialize, serde::Serialize)]
pub struct PaymentListFilterConstraints {
/// The identifier for payment
pub payment_id: Option<String>,
@@ -3100,7 +3100,7 @@ pub struct PaymentLinkObject {
pub merchant_custom_domain_name: Option<String>,
}
-#[derive(Default, Debug, serde::Deserialize, Clone, ToSchema)]
+#[derive(Default, Debug, serde::Deserialize, Clone, ToSchema, serde::Serialize)]
pub struct RetrievePaymentLinkRequest {
pub client_secret: Option<String>,
}
@@ -3128,7 +3128,7 @@ pub struct RetrievePaymentLinkResponse {
pub link_expiry: Option<PrimitiveDateTime>,
}
-#[derive(Clone, Debug, serde::Deserialize, ToSchema)]
+#[derive(Clone, Debug, serde::Deserialize, ToSchema, serde::Serialize)]
pub struct PaymentLinkInitiateRequest {
pub merchant_id: String,
pub payment_id: String,
diff --git a/crates/api_models/src/refunds.rs b/crates/api_models/src/refunds.rs
index ceb476fff3..7b4eae4238 100644
--- a/crates/api_models/src/refunds.rs
+++ b/crates/api_models/src/refunds.rs
@@ -5,7 +5,7 @@ use utoipa::ToSchema;
use crate::{admin, enums};
-#[derive(Default, Debug, ToSchema, Clone, Deserialize)]
+#[derive(Default, Debug, ToSchema, Clone, Deserialize, Serialize)]
#[serde(deny_unknown_fields)]
pub struct RefundRequest {
/// Unique Identifier for the Refund. This is to ensure idempotency for multiple partial refund initiated against the same payment. If the identifiers is not defined by the merchant, this filed shall be auto generated and provide in the API response. It is recommended to generate uuid(v4) as the refund_id.
@@ -54,7 +54,7 @@ pub struct RefundsRetrieveBody {
pub force_sync: Option<bool>,
}
-#[derive(Default, Debug, ToSchema, Clone, Deserialize)]
+#[derive(Default, Debug, ToSchema, Clone, Deserialize, Serialize)]
pub struct RefundsRetrieveRequest {
/// Unique Identifier for the Refund. This is to ensure idempotency for multiple partial refund initiated against the same payment. If the identifiers is not defined by the merchant, this filed shall be auto generated and provide in the API response. It is recommended to generate uuid(v4) as the refund_id.
#[schema(
@@ -72,7 +72,7 @@ pub struct RefundsRetrieveRequest {
pub merchant_connector_details: Option<admin::MerchantConnectorDetailsWrap>,
}
-#[derive(Default, Debug, ToSchema, Clone, Deserialize)]
+#[derive(Default, Debug, ToSchema, Clone, Deserialize, Serialize)]
#[serde(deny_unknown_fields)]
pub struct RefundUpdateRequest {
/// An arbitrary string attached to the object. Often useful for displaying to users and your customer support executive
diff --git a/crates/masking/src/lib.rs b/crates/masking/src/lib.rs
index a0c4d3226a..d092a1b5a8 100644
--- a/crates/masking/src/lib.rs
+++ b/crates/masking/src/lib.rs
@@ -42,7 +42,7 @@ mod vec;
#[cfg(feature = "serde")]
mod serde;
#[cfg(feature = "serde")]
-pub use crate::serde::{Deserialize, SerializableSecret, Serialize};
+pub use crate::serde::{masked_serialize, Deserialize, SerializableSecret, Serialize};
/// This module should be included with asterisk.
///
diff --git a/crates/masking/src/serde.rs b/crates/masking/src/serde.rs
index abdc117b61..e57ed0301c 100644
--- a/crates/masking/src/serde.rs
+++ b/crates/masking/src/serde.rs
@@ -2,9 +2,10 @@
//! Serde-related.
//!
-pub use serde::{de, ser, Deserialize, Serialize};
+pub use serde::{de, ser, Deserialize, Serialize, Serializer};
+use serde_json::{value::Serializer as JsonValueSerializer, Value};
-use crate::{PeekInterface, Secret, Strategy, StrongSecret, ZeroizableSecret};
+use crate::{Secret, Strategy, StrongSecret, ZeroizableSecret};
/// Marker trait for secret types which can be [`Serialize`]-d by [`serde`].
///
@@ -22,7 +23,7 @@ pub trait SerializableSecret: Serialize {}
// #[cfg_attr(docsrs, doc(cfg(feature = "serde")))]
// pub trait NonSerializableSecret: Serialize {}
-impl SerializableSecret for serde_json::Value {}
+impl SerializableSecret for Value {}
impl SerializableSecret for u8 {}
impl SerializableSecret for u16 {}
@@ -46,9 +47,9 @@ where
{
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
- S: ser::Serializer,
+ S: Serializer,
{
- self.peek().serialize(serializer)
+ pii_serializer::pii_serialize(self, serializer)
}
}
@@ -72,8 +73,451 @@ where
{
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
- S: serde::Serializer,
+ S: Serializer,
{
- self.peek().serialize(serializer)
+ pii_serializer::pii_serialize(self, serializer)
+ }
+}
+
+///
+/// Masked serialization.
+///
+/// the default behaviour for secrets is to serialize in exposed format since the common use cases
+/// for storing the secret to database or sending it over the network requires the secret to be exposed
+/// This method allows to serialize the secret in masked format if needed for logs or other insecure exposures
+pub fn masked_serialize<T: Serialize>(value: &T) -> Result<Value, serde_json::Error> {
+ value.serialize(PIISerializer {
+ inner: JsonValueSerializer,
+ })
+}
+
+use pii_serializer::PIISerializer;
+
+mod pii_serializer {
+ use std::fmt::Display;
+
+ pub(super) fn pii_serialize<
+ V: Serialize,
+ T: std::fmt::Debug + PeekInterface<V>,
+ S: Serializer,
+ >(
+ value: &T,
+ serializer: S,
+ ) -> Result<S::Ok, S::Error> {
+ // Mask the value if the serializer is of type PIISerializer
+ // or send empty map if the serializer is of type FlatMapSerializer over PiiSerializer
+ if std::any::type_name::<S>() == std::any::type_name::<PIISerializer>() {
+ format!("{value:?}").serialize(serializer)
+ } else if std::any::type_name::<S>()
+ == std::any::type_name::<
+ serde::__private::ser::FlatMapSerializer<'_, SerializeMap<PIISerializer>>,
+ >()
+ {
+ std::collections::HashMap::<String, String>::from([]).serialize(serializer)
+ } else {
+ value.peek().serialize(serializer)
+ }
+ }
+
+ use serde::{Serialize, Serializer};
+ use serde_json::{value::Serializer as JsonValueSerializer, Map, Value};
+
+ use crate::PeekInterface;
+
+ pub(super) struct PIISerializer {
+ pub inner: JsonValueSerializer,
+ }
+
+ impl Clone for PIISerializer {
+ fn clone(&self) -> Self {
+ Self {
+ inner: JsonValueSerializer,
+ }
+ }
+ }
+
+ impl Serializer for PIISerializer {
+ type Ok = Value;
+ type Error = serde_json::Error;
+
+ type SerializeSeq = SerializeVec<Self>;
+ type SerializeTuple = SerializeVec<Self>;
+ type SerializeTupleStruct = SerializeVec<Self>;
+ type SerializeTupleVariant = SerializeTupleVariant<Self>;
+ type SerializeMap = SerializeMap<Self>;
+ type SerializeStruct = SerializeMap<Self>;
+ type SerializeStructVariant = SerializeStructVariant<Self>;
+
+ #[inline]
+ fn serialize_bool(self, value: bool) -> Result<Self::Ok, Self::Error> {
+ self.inner.serialize_bool(value)
+ }
+
+ #[inline]
+ fn serialize_i8(self, value: i8) -> Result<Self::Ok, Self::Error> {
+ self.serialize_i64(value.into())
+ }
+
+ #[inline]
+ fn serialize_i16(self, value: i16) -> Result<Self::Ok, Self::Error> {
+ self.serialize_i64(value.into())
+ }
+
+ #[inline]
+ fn serialize_i32(self, value: i32) -> Result<Self::Ok, Self::Error> {
+ self.serialize_i64(value.into())
+ }
+
+ fn serialize_i64(self, value: i64) -> Result<Self::Ok, Self::Error> {
+ self.inner.serialize_i64(value)
+ }
+
+ fn serialize_i128(self, value: i128) -> Result<Self::Ok, Self::Error> {
+ self.inner.serialize_i128(value)
+ }
+
+ #[inline]
+ fn serialize_u8(self, value: u8) -> Result<Self::Ok, Self::Error> {
+ self.serialize_u64(value.into())
+ }
+
+ #[inline]
+ fn serialize_u16(self, value: u16) -> Result<Self::Ok, Self::Error> {
+ self.serialize_u64(value.into())
+ }
+
+ #[inline]
+ fn serialize_u32(self, value: u32) -> Result<Self::Ok, Self::Error> {
+ self.serialize_u64(value.into())
+ }
+
+ #[inline]
+ fn serialize_u64(self, value: u64) -> Result<Self::Ok, Self::Error> {
+ Ok(Value::Number(value.into()))
+ }
+
+ fn serialize_u128(self, value: u128) -> Result<Self::Ok, Self::Error> {
+ self.inner.serialize_u128(value)
+ }
+
+ #[inline]
+ fn serialize_f32(self, float: f32) -> Result<Self::Ok, Self::Error> {
+ Ok(Value::from(float))
+ }
+
+ #[inline]
+ fn serialize_f64(self, float: f64) -> Result<Self::Ok, Self::Error> {
+ Ok(Value::from(float))
+ }
+
+ #[inline]
+ fn serialize_char(self, value: char) -> Result<Self::Ok, Self::Error> {
+ let mut s = String::new();
+ s.push(value);
+ Ok(Value::String(s))
+ }
+
+ #[inline]
+ fn serialize_str(self, value: &str) -> Result<Self::Ok, Self::Error> {
+ Ok(Value::String(value.to_owned()))
+ }
+
+ fn serialize_bytes(self, value: &[u8]) -> Result<Self::Ok, Self::Error> {
+ let vec = value.iter().map(|&b| Value::Number(b.into())).collect();
+ Ok(Value::Array(vec))
+ }
+
+ #[inline]
+ fn serialize_unit(self) -> Result<Self::Ok, Self::Error> {
+ Ok(Value::Null)
+ }
+
+ #[inline]
+ fn serialize_unit_struct(self, _name: &'static str) -> Result<Self::Ok, Self::Error> {
+ self.serialize_unit()
+ }
+
+ #[inline]
+ fn serialize_unit_variant(
+ self,
+ _name: &'static str,
+ _variant_index: u32,
+ variant: &'static str,
+ ) -> Result<Self::Ok, Self::Error> {
+ self.serialize_str(variant)
+ }
+
+ #[inline]
+ fn serialize_newtype_struct<T>(
+ self,
+ _name: &'static str,
+ value: &T,
+ ) -> Result<Self::Ok, Self::Error>
+ where
+ T: ?Sized + Serialize,
+ {
+ value.serialize(self)
+ }
+
+ fn serialize_newtype_variant<T>(
+ self,
+ _name: &'static str,
+ _variant_index: u32,
+ variant: &'static str,
+ value: &T,
+ ) -> Result<Self::Ok, Self::Error>
+ where
+ T: ?Sized + Serialize,
+ {
+ let mut values = Map::new();
+ values.insert(String::from(variant), value.serialize(self)?);
+ Ok(Value::Object(values))
+ }
+
+ #[inline]
+ fn serialize_none(self) -> Result<Self::Ok, Self::Error> {
+ self.serialize_unit()
+ }
+
+ #[inline]
+ fn serialize_some<T>(self, value: &T) -> Result<Self::Ok, Self::Error>
+ where
+ T: ?Sized + Serialize,
+ {
+ value.serialize(self)
+ }
+
+ fn serialize_seq(self, len: Option<usize>) -> Result<Self::SerializeSeq, Self::Error> {
+ Ok(SerializeVec {
+ vec: Vec::with_capacity(len.unwrap_or(0)),
+ ser: self,
+ })
+ }
+
+ fn serialize_tuple(self, len: usize) -> Result<Self::SerializeTuple, Self::Error> {
+ self.serialize_seq(Some(len))
+ }
+
+ fn serialize_tuple_struct(
+ self,
+ _name: &'static str,
+ len: usize,
+ ) -> Result<Self::SerializeTupleStruct, Self::Error> {
+ self.serialize_seq(Some(len))
+ }
+
+ fn serialize_tuple_variant(
+ self,
+ _name: &'static str,
+ _variant_index: u32,
+ variant: &'static str,
+ len: usize,
+ ) -> Result<Self::SerializeTupleVariant, Self::Error> {
+ Ok(SerializeTupleVariant {
+ name: String::from(variant),
+ vec: Vec::with_capacity(len),
+ ser: self,
+ })
+ }
+
+ fn serialize_map(self, len: Option<usize>) -> Result<Self::SerializeMap, Self::Error> {
+ Ok(SerializeMap {
+ inner: self.clone().inner.serialize_map(len)?,
+ ser: self,
+ })
+ }
+
+ fn serialize_struct(
+ self,
+ _name: &'static str,
+ len: usize,
+ ) -> Result<Self::SerializeStruct, Self::Error> {
+ self.serialize_map(Some(len))
+ }
+
+ fn serialize_struct_variant(
+ self,
+ _name: &'static str,
+ _variant_index: u32,
+ variant: &'static str,
+ _len: usize,
+ ) -> Result<Self::SerializeStructVariant, Self::Error> {
+ Ok(SerializeStructVariant {
+ name: String::from(variant),
+ map: Map::new(),
+ ser: self,
+ })
+ }
+
+ fn collect_str<T>(self, value: &T) -> Result<Self::Ok, Self::Error>
+ where
+ T: ?Sized + Display,
+ {
+ self.inner.collect_str(value)
+ }
+ }
+
+ pub(super) struct SerializeVec<T: Serializer> {
+ vec: Vec<Value>,
+ ser: T,
+ }
+
+ impl<T: Serializer<Ok = Value> + Clone> serde::ser::SerializeSeq for SerializeVec<T> {
+ type Ok = Value;
+ type Error = T::Error;
+
+ fn serialize_element<V>(&mut self, value: &V) -> Result<(), Self::Error>
+ where
+ V: ?Sized + Serialize,
+ {
+ self.vec.push(value.serialize(self.ser.clone())?);
+ Ok(())
+ }
+
+ fn end(self) -> Result<Self::Ok, Self::Error> {
+ Ok(Value::Array(self.vec))
+ }
+ }
+
+ impl<T: Serializer<Ok = Value> + Clone> serde::ser::SerializeTuple for SerializeVec<T> {
+ type Ok = Value;
+ type Error = T::Error;
+
+ fn serialize_element<V>(&mut self, value: &V) -> Result<(), Self::Error>
+ where
+ V: ?Sized + Serialize,
+ {
+ serde::ser::SerializeSeq::serialize_element(self, value)
+ }
+
+ fn end(self) -> Result<Self::Ok, Self::Error> {
+ serde::ser::SerializeSeq::end(self)
+ }
+ }
+
+ impl<T: Serializer<Ok = Value> + Clone> serde::ser::SerializeTupleStruct for SerializeVec<T> {
+ type Ok = Value;
+ type Error = T::Error;
+
+ fn serialize_field<V>(&mut self, value: &V) -> Result<(), Self::Error>
+ where
+ V: ?Sized + Serialize,
+ {
+ serde::ser::SerializeSeq::serialize_element(self, value)
+ }
+
+ fn end(self) -> Result<Self::Ok, Self::Error> {
+ serde::ser::SerializeSeq::end(self)
+ }
+ }
+
+ pub(super) struct SerializeStructVariant<T: Serializer> {
+ name: String,
+ map: Map<String, Value>,
+ ser: T,
+ }
+
+ impl<T: Serializer<Ok = Value> + Clone> serde::ser::SerializeStructVariant
+ for SerializeStructVariant<T>
+ {
+ type Ok = Value;
+ type Error = T::Error;
+
+ fn serialize_field<V>(&mut self, key: &'static str, value: &V) -> Result<(), Self::Error>
+ where
+ V: ?Sized + Serialize,
+ {
+ self.map
+ .insert(String::from(key), value.serialize(self.ser.clone())?);
+ Ok(())
+ }
+
+ fn end(self) -> Result<Self::Ok, Self::Error> {
+ let mut object = Map::new();
+
+ object.insert(self.name, Value::Object(self.map));
+
+ Ok(Value::Object(object))
+ }
+ }
+
+ pub(super) struct SerializeTupleVariant<T: Serializer> {
+ name: String,
+ vec: Vec<Value>,
+ ser: T,
+ }
+
+ impl<T: Serializer<Ok = Value> + Clone> serde::ser::SerializeTupleVariant
+ for SerializeTupleVariant<T>
+ {
+ type Ok = Value;
+ type Error = T::Error;
+
+ fn serialize_field<V>(&mut self, value: &V) -> Result<(), Self::Error>
+ where
+ V: ?Sized + Serialize,
+ {
+ self.vec.push(value.serialize(self.ser.clone())?);
+ Ok(())
+ }
+
+ fn end(self) -> Result<Value, Self::Error> {
+ let mut object = Map::new();
+
+ object.insert(self.name, Value::Array(self.vec));
+
+ Ok(Value::Object(object))
+ }
+ }
+
+ pub(super) struct SerializeMap<T: Serializer> {
+ inner: <serde_json::value::Serializer as Serializer>::SerializeMap,
+ ser: T,
+ }
+
+ impl<T: Serializer<Ok = Value, Error = serde_json::Error> + Clone> serde::ser::SerializeMap
+ for SerializeMap<T>
+ {
+ type Ok = Value;
+ type Error = T::Error;
+
+ fn serialize_key<V>(&mut self, key: &V) -> Result<(), Self::Error>
+ where
+ V: ?Sized + Serialize,
+ {
+ self.inner.serialize_key(key)?;
+ Ok(())
+ }
+
+ fn serialize_value<V>(&mut self, value: &V) -> Result<(), Self::Error>
+ where
+ V: ?Sized + Serialize,
+ {
+ let value = value.serialize(self.ser.clone())?;
+ self.inner.serialize_value(&value)?;
+ Ok(())
+ }
+
+ fn end(self) -> Result<Value, Self::Error> {
+ self.inner.end()
+ }
+ }
+
+ impl<T: Serializer<Ok = Value, Error = serde_json::Error> + Clone> serde::ser::SerializeStruct
+ for SerializeMap<T>
+ {
+ type Ok = Value;
+ type Error = T::Error;
+
+ fn serialize_field<V>(&mut self, key: &'static str, value: &V) -> Result<(), Self::Error>
+ where
+ V: ?Sized + Serialize,
+ {
+ serde::ser::SerializeMap::serialize_entry(self, key, value)
+ }
+
+ fn end(self) -> Result<Value, Self::Error> {
+ serde::ser::SerializeMap::end(self)
+ }
}
}
diff --git a/crates/router/src/compatibility/wrap.rs b/crates/router/src/compatibility/wrap.rs
index f1892698ac..8a1bf3f6ae 100644
--- a/crates/router/src/compatibility/wrap.rs
+++ b/crates/router/src/compatibility/wrap.rs
@@ -31,7 +31,7 @@ where
U: auth::AuthInfo,
error_stack::Report<E>: services::EmbedError,
errors::ApiErrorResponse: ErrorSwitch<E>,
- T: std::fmt::Debug,
+ T: std::fmt::Debug + Serialize,
A: AppStateInfo + Clone,
{
let request_method = request.method().as_str();
diff --git a/crates/router/src/core/payments.rs b/crates/router/src/core/payments.rs
index 7d6cf04dd9..ab56a4b35a 100644
--- a/crates/router/src/core/payments.rs
+++ b/crates/router/src/core/payments.rs
@@ -318,7 +318,7 @@ fn is_start_pay<Op: Debug>(operation: &Op) -> bool {
format!("{operation:?}").eq("PaymentStart")
}
-#[derive(Clone, Debug)]
+#[derive(Clone, Debug, serde::Serialize)]
pub struct PaymentsRedirectResponseData {
pub connector: Option<String>,
pub param: Option<String>,
diff --git a/crates/router/src/events/api_logs.rs b/crates/router/src/events/api_logs.rs
index ee6676b9e4..5e031fd945 100644
--- a/crates/router/src/events/api_logs.rs
+++ b/crates/router/src/events/api_logs.rs
@@ -11,8 +11,8 @@ pub struct ApiEvent {
request_id: String,
latency: u128,
status_code: i64,
- request: String,
- response: String,
+ request: serde_json::Value,
+ response: Option<serde_json::Value>,
}
impl ApiEvent {
@@ -21,8 +21,8 @@ impl ApiEvent {
request_id: &RequestId,
latency: u128,
status_code: i64,
- request: String,
- response: String,
+ request: serde_json::Value,
+ response: Option<serde_json::Value>,
) -> Self {
Self {
api_flow: api_flow.to_string(),
diff --git a/crates/router/src/routes/webhooks.rs b/crates/router/src/routes/webhooks.rs
index f9fee54d16..5c90e46bb9 100644
--- a/crates/router/src/routes/webhooks.rs
+++ b/crates/router/src/routes/webhooks.rs
@@ -25,15 +25,15 @@ pub async fn receive_incoming_webhook<W: types::OutgoingWebhookType>(
flow,
state,
&req,
- body,
- |state, auth, body| {
+ (),
+ |state, auth, _| {
webhooks::webhooks_wrapper::<W, Oss>(
state.to_owned(),
&req,
auth.merchant_account,
auth.key_store,
&connector_id_or_name,
- body,
+ body.clone(),
)
},
&auth::MerchantIdAuth(merchant_id),
diff --git a/crates/router/src/services/api.rs b/crates/router/src/services/api.rs
index b21eff3e7a..cb94312b0e 100644
--- a/crates/router/src/services/api.rs
+++ b/crates/router/src/services/api.rs
@@ -759,7 +759,7 @@ where
'b: 'a,
Fut: Future<Output = CustomResult<ApplicationResponse<Q>, E>>,
Q: Serialize + Debug + 'a,
- T: Debug,
+ T: Debug + Serialize,
A: AppStateInfo + Clone,
U: AuthInfo,
E: ErrorSwitch<OErr> + error_stack::Context,
@@ -776,7 +776,12 @@ where
request_state.add_request_id(request_id);
let start_instant = Instant::now();
+ let serialized_request = masking::masked_serialize(&payload)
+ .into_report()
+ .attach_printable("Failed to serialize json request")
+ .change_context(errors::ApiErrorResponse::InternalServerError.switch())?;
+ // Currently auth failures are not recorded as API events
let auth_out = api_auth
.authenticate_and_fetch(request.headers(), &request_state)
.await
@@ -793,7 +798,6 @@ where
tracing::Span::current().record("merchant_id", &merchant_id);
- let req_message = format!("{:?}", payload);
let output = {
lock_action
.clone()
@@ -813,17 +817,30 @@ where
.saturating_duration_since(start_instant)
.as_millis();
+ let mut serialized_response = None;
let status_code = match output.as_ref() {
- Ok(res) => metrics::request::track_response_status_code(res),
+ Ok(res) => {
+ if let ApplicationResponse::Json(data) = res {
+ serialized_response.replace(
+ masking::masked_serialize(&data)
+ .into_report()
+ .attach_printable("Failed to serialize json response")
+ .change_context(errors::ApiErrorResponse::InternalServerError.switch())?,
+ );
+ }
+
+ metrics::request::track_response_status_code(res)
+ }
Err(err) => err.current_context().status_code().as_u16().into(),
};
+
let api_event = ApiEvent::new(
flow,
&request_id,
request_duration,
status_code,
- req_message,
- format!("{:?}", output),
+ serialized_request,
+ serialized_response,
);
match api_event.clone().try_into() {
Ok(event) => {
@@ -856,7 +873,7 @@ where
F: Fn(A, U, T) -> Fut,
Fut: Future<Output = CustomResult<ApplicationResponse<Q>, E>>,
Q: Serialize + Debug + 'a,
- T: Debug,
+ T: Debug + Serialize,
U: AuthInfo,
A: AppStateInfo + Clone,
ApplicationResponse<Q>: Debug,
diff --git a/crates/router/src/types.rs b/crates/router/src/types.rs
index 2f1bce49e0..9f1dbad142 100644
--- a/crates/router/src/types.rs
+++ b/crates/router/src/types.rs
@@ -834,10 +834,12 @@ pub struct DefendDisputeResponse {
pub connector_status: Option<String>,
}
-#[derive(Clone, Debug)]
+#[derive(Clone, Debug, serde::Serialize)]
pub struct UploadFileRequestData {
pub file_key: String,
+ #[serde(skip)]
pub file: Vec<u8>,
+ #[serde(serialize_with = "crate::utils::custom_serde::display_serialize")]
pub file_type: mime::Mime,
pub file_size: i32,
}
diff --git a/crates/router/src/types/api/configs.rs b/crates/router/src/types/api/configs.rs
index 9e39d5569b..dbe8b0603a 100644
--- a/crates/router/src/types/api/configs.rs
+++ b/crates/router/src/types/api/configs.rs
@@ -4,7 +4,7 @@ pub struct Config {
pub value: String,
}
-#[derive(Clone, serde::Deserialize, Debug)]
+#[derive(Clone, serde::Deserialize, Debug, serde::Serialize)]
pub struct ConfigUpdate {
#[serde(skip_deserializing)]
pub key: String,
diff --git a/crates/router/src/types/api/disputes.rs b/crates/router/src/types/api/disputes.rs
index 4339554fdc..85fdb307ed 100644
--- a/crates/router/src/types/api/disputes.rs
+++ b/crates/router/src/types/api/disputes.rs
@@ -36,13 +36,13 @@ pub struct DisputeEvidence {
pub uncategorized_file: Option<String>,
}
-#[derive(Debug, Clone)]
+#[derive(Debug, Clone, Serialize)]
pub struct AttachEvidenceRequest {
pub create_file_request: types::api::CreateFileRequest,
pub evidence_type: EvidenceType,
}
-#[derive(Debug, serde::Deserialize, strum::Display, strum::EnumString, Clone)]
+#[derive(Debug, serde::Deserialize, strum::Display, strum::EnumString, Clone, serde::Serialize)]
#[serde(rename_all = "snake_case")]
#[strum(serialize_all = "snake_case")]
pub enum EvidenceType {
diff --git a/crates/router/src/types/api/files.rs b/crates/router/src/types/api/files.rs
index 1e78708c81..873516ee71 100644
--- a/crates/router/src/types/api/files.rs
+++ b/crates/router/src/types/api/files.rs
@@ -47,17 +47,18 @@ impl ForeignTryFrom<&types::Connector> for FileUploadProvider {
}
}
-#[derive(Debug, Clone)]
+#[derive(Debug, Clone, serde::Serialize)]
pub struct CreateFileRequest {
pub file: Vec<u8>,
pub file_name: Option<String>,
pub file_size: i32,
+ #[serde(serialize_with = "crate::utils::custom_serde::display_serialize")]
pub file_type: mime::Mime,
pub purpose: FilePurpose,
pub dispute_id: Option<String>,
}
-#[derive(Debug, serde::Deserialize, strum::Display, Clone)]
+#[derive(Debug, serde::Deserialize, strum::Display, Clone, serde::Serialize)]
#[serde(rename_all = "snake_case")]
#[strum(serialize_all = "snake_case")]
pub enum FilePurpose {
diff --git a/crates/router/src/utils/custom_serde.rs b/crates/router/src/utils/custom_serde.rs
index 8b13789179..dcdad3092b 100644
--- a/crates/router/src/utils/custom_serde.rs
+++ b/crates/router/src/utils/custom_serde.rs
@@ -1 +1,7 @@
-
+pub fn display_serialize<T, S>(value: &T, serializer: S) -> Result<S::Ok, S::Error>
+where
+ T: std::fmt::Display,
+ S: serde::ser::Serializer,
+{
+ serializer.serialize_str(&format!("{}", value))
+}
diff --git a/docker-compose.yml b/docker-compose.yml
index 1fe487da5a..f4dce57513 100644
--- a/docker-compose.yml
+++ b/docker-compose.yml
@@ -72,7 +72,7 @@ services:
pg:
image: postgres:14.5
ports:
- - "5432"
+ - "5432:5432"
networks:
- router_net
volumes: