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(Proxy): Including support for extended content/types - xml in vault-proxy flows (#15164)

Ritam Kabirajcf5408d83e89
diff --git a/Cargo.lock b/Cargo.lock
index 0fd0093aaa..e1c5634074 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -2212,6 +2212,7 @@ dependencies = [
"hyperswitch_masking",
"ip_network",
"md5",
+ "mime",
"nanoid",
"nutype",
"once_cell",
@@ -8072,6 +8073,7 @@ dependencies = [
"payment_methods",
"pm_auth",
"prost-types 0.14.3",
+ "quick-xml",
"rand 0.8.6",
"rand_chacha 0.3.1",
"rdkafka",
@@ -8081,6 +8083,7 @@ dependencies = [
"ring 0.17.14",
"router_derive",
"router_env",
+ "roxmltree",
"rust-grpc-client",
"rust-i18n",
"rust_decimal",
diff --git a/api-reference/v2/openapi_spec_v2.json b/api-reference/v2/openapi_spec_v2.json
index 35f82fed84..fda40fe036 100644
--- a/api-reference/v2/openapi_spec_v2.json
+++ b/api-reference/v2/openapi_spec_v2.json
@@ -31491,7 +31491,7 @@
],
"properties": {
"request_body": {
- "description": "The request body that needs to be forwarded"
+ "description": "The request body that needs to be forwarded: JSON, or an XML document as a string with\nan XML Content-Type. Other Content-Types are rejected. GET and DELETE send no body."
},
"destination_url": {
"type": "string",
@@ -31524,7 +31524,7 @@
],
"properties": {
"response": {
- "description": "The response received from the destination"
+ "$ref": "#/components/schemas/ProxyResponseBody"
},
"status_code": {
"type": "integer",
@@ -31538,6 +31538,18 @@
}
}
},
+ "ProxyResponseBody": {
+ "oneOf": [
+ {
+ "description": "A JSON body"
+ },
+ {
+ "type": "string",
+ "description": "Any other body, as UTF-8 text"
+ }
+ ],
+ "description": "The destination's response body: JSON when it parses as JSON, otherwise its text, such\nas an XML document. Only UTF-8 text is supported. Both variants serialize to the bare\nvalue, so a JSON string and text look the same on the wire; this type is serialize-only."
+ },
"PspTokenization": {
"type": "object",
"description": "The Payment Service Provider Configuration for payment methods that are created using the payment method session",
diff --git a/crates/api_models/src/proxy.rs b/crates/api_models/src/proxy.rs
index 63e2c64a4d..b68be00ca8 100644
--- a/crates/api_models/src/proxy.rs
+++ b/crates/api_models/src/proxy.rs
@@ -29,7 +29,8 @@ impl Headers {
#[derive(Debug, ToSchema, Clone, Deserialize, Serialize)]
pub struct ProxyRequest {
- /// The request body that needs to be forwarded
+ /// The request body that needs to be forwarded: JSON, or an XML document as a string with
+ /// an XML Content-Type. Other Content-Types are rejected. GET and DELETE send no body.
pub request_body: Value,
/// The non-empty HTTP or HTTPS destination URL. Configured proxy bypass hosts are rejected.
/// IP literals must be publicly routable.
@@ -57,10 +58,10 @@ pub enum TokenType {
PaymentMethodToken,
}
-#[derive(Debug, ToSchema, Clone, Deserialize, Serialize)]
+#[derive(Debug, ToSchema, Clone, Serialize)]
pub struct ProxyResponse {
/// The response received from the destination
- pub response: Value,
+ pub response: ProxyResponseBody,
/// The status code of the response
pub status_code: u16,
/// The headers of the response
@@ -68,6 +69,18 @@ pub struct ProxyResponse {
pub response_headers: Headers,
}
+/// The destination's response body: JSON when it parses as JSON, otherwise its text, such
+/// as an XML document. Only UTF-8 text is supported. Both variants serialize to the bare
+/// value, so a JSON string and text look the same on the wire; this type is serialize-only.
+#[derive(Debug, ToSchema, Clone, Serialize)]
+#[serde(untagged)]
+pub enum ProxyResponseBody {
+ /// A JSON body
+ Json(Value),
+ /// Any other body, as UTF-8 text
+ Text(String),
+}
+
impl common_utils::events::ApiEventMetric for ProxyRequest {}
impl common_utils::events::ApiEventMetric for ProxyResponse {}
diff --git a/crates/common_utils/Cargo.toml b/crates/common_utils/Cargo.toml
index 69e664aec9..7dd7bcff7b 100644
--- a/crates/common_utils/Cargo.toml
+++ b/crates/common_utils/Cargo.toml
@@ -41,6 +41,7 @@ hex = "0.4.3"
http = "0.2.12"
ip_network = { version = "0.4.1", default-features = false }
md5 = "0.7.0"
+mime = "0.3.17"
nanoid = "0.4.0"
nutype = { version = "0.4.3", features = ["serde"] }
once_cell = "1.21.3"
diff --git a/crates/common_utils/src/request.rs b/crates/common_utils/src/request.rs
index 3fe7e9191d..a4937edcd0 100644
--- a/crates/common_utils/src/request.rs
+++ b/crates/common_utils/src/request.rs
@@ -64,6 +64,52 @@ pub enum ContentType {
Xml,
}
+/// A connector Content-Type header, parsed once and passed to every step that needs it.
+#[derive(Debug)]
+pub struct ConnectorContentType<'a> {
+ header: &'a str,
+ mime: mime::Mime,
+}
+
+impl<'a> ConnectorContentType<'a> {
+ /// Parse a Content-Type header value; `None` when it is not a valid MIME type.
+ pub fn parse(header: &'a str) -> Option<Self> {
+ header
+ .parse::<mime::Mime>()
+ .ok()
+ .map(|mime| Self { header, mime })
+ }
+
+ /// The body format this header declares, for the formats the proxy handles.
+ pub fn kind(&self) -> Option<ContentType> {
+ match self.mime.essence_str() {
+ "application/json" => Some(ContentType::Json),
+ "application/xml" | "text/xml" => Some(ContentType::Xml),
+ kind if kind.ends_with("+json") => Some(ContentType::Json),
+ kind if kind.ends_with("+xml") => Some(ContentType::Xml),
+ _ => None,
+ }
+ }
+
+ /// The header value as received.
+ pub fn header(&self) -> &'a str {
+ self.header
+ }
+
+ /// Whether the charset, if declared, is UTF-8. Templates are UTF-8, so a conflicting
+ /// declaration would make the connector decode the bytes incorrectly.
+ pub fn is_utf8(&self) -> bool {
+ self.mime
+ .params()
+ .all(|(name, value)| name != mime::CHARSET || is_utf8_label(value.as_str().as_bytes()))
+ }
+}
+
+/// Whether a charset or XML encoding label names UTF-8.
+pub fn is_utf8_label(label: &[u8]) -> bool {
+ label.eq_ignore_ascii_case(b"utf-8") || label.eq_ignore_ascii_case(b"utf8")
+}
+
fn default_request_headers() -> [(String, Maskable<String>); 1] {
use http::header;
diff --git a/crates/injector/src/types.rs b/crates/injector/src/types.rs
index 20f7bd1d41..2706b2e5ee 100644
--- a/crates/injector/src/types.rs
+++ b/crates/injector/src/types.rs
@@ -2,10 +2,13 @@ pub mod models {
use std::collections::HashMap;
use async_trait::async_trait;
- use common_utils::pii::SecretSerdeValue;
+ use common_utils::{pii::SecretSerdeValue, request::ConnectorContentType};
use hyperswitch_masking::{ExposeInterface, Secret};
use router_env::logger;
use serde::{Deserialize, Serialize};
+ use serde_json::Value;
+
+ use crate::InjectorError;
// Enums for the injector - making it standalone
@@ -166,7 +169,7 @@ pub mod models {
pub struct HyperswitchVaultProxyRequest {
/// The connector request body template with {{$field_name}} placeholders.
/// HS Vault will resolve these with actual card data before forwarding.
- pub request_body: serde_json::Value,
+ pub request_body: Value,
/// The connector's actual endpoint URL (e.g. "https://api.sandbox.checkout.com/payments")
pub destination_url: url::Url,
/// The connector's headers (Content-Type, Authorization, etc.)
@@ -189,7 +192,7 @@ pub mod models {
processed_payload: &str,
connection_config: &ConnectionConfig,
token_data: &TokenData,
- ) -> Result<Self, crate::injector::core::InjectorError> {
+ ) -> Result<Self, InjectorError> {
// Extract the single token from card_number field in specific_token_data
let vault_data = token_data.specific_token_data.clone().expose();
let token = vault_data
@@ -198,7 +201,7 @@ pub mod models {
.and_then(|v| v.as_str())
.map(|s| s.to_string())
.ok_or_else(|| {
- crate::injector::core::InjectorError::InvalidTemplate(
+ InjectorError::InvalidTemplate(
"card_number field is required in specific_token_data for HyperswitchVault"
.to_string(),
)
@@ -206,8 +209,8 @@ pub mod models {
// Parse the processed payload as JSON value.
// The template may be JSON or form-urlencoded; wrap non-JSON as a string value.
- let request_body = serde_json::from_str::<serde_json::Value>(processed_payload)
- .unwrap_or_else(|_| serde_json::Value::String(processed_payload.to_string()));
+ let request_body = serde_json::from_str::<Value>(processed_payload)
+ .unwrap_or_else(|_| Value::String(processed_payload.to_string()));
// Convert connector headers from Secret<String> → plain String for the vault request
let headers: HashMap<String, Secret<String>> = connection_config
@@ -248,23 +251,101 @@ pub mod models {
/// Response headers from the connector (optional)
pub headers: Option<HashMap<String, String>>,
/// Response body from the connector
- pub response: serde_json::Value,
+ pub response: Value,
+ }
+
+ /// The Hyperswitch vault proxy reply (`api_models::proxy::ProxyResponse`), which wraps
+ /// the connector response.
+ #[derive(Deserialize)]
+ struct VaultProxyEnvelope {
+ status_code: u16,
+ response: Value,
+ response_headers: Option<HashMap<String, String>>,
+ }
+
+ /// The connector response, taken from a direct connector reply or a vault proxy reply.
+ pub struct InjectorConnectorResponse {
+ pub status_code: u16,
+ pub headers: Option<Vec<(String, String)>>,
+ pub body: Vec<u8>,
+ }
+
+ impl InjectorResponse {
+ /// The vault proxy reply wrapping the connector response. A non-2xx outer status means
+ /// the proxy call itself failed; the wrapped status must be a valid HTTP status.
+ fn vault_proxy_envelope(&self) -> Result<VaultProxyEnvelope, InjectorError> {
+ if (200..=299).contains(&self.status_code) {
+ VaultProxyEnvelope::deserialize(&self.response)
+ .ok()
+ .filter(|envelope| (100..=599).contains(&envelope.status_code))
+ .ok_or_else(|| {
+ InjectorError::InvalidTemplate("Invalid vault proxy response".into())
+ })
+ } else {
+ Err(InjectorError::HttpRequestFailed)
+ }
+ }
+
+ /// The actual connector response. Only the HyperswitchVault envelope is unwrapped:
+ /// direct connector replies may legitimately contain fields called `response` and
+ /// `status_code`.
+ pub fn into_connector_response(
+ self,
+ wrapped: bool,
+ ) -> Result<InjectorConnectorResponse, InjectorError> {
+ let (status_code, headers, response) = if wrapped {
+ let envelope = self.vault_proxy_envelope()?;
+ (
+ envelope.status_code,
+ envelope.response_headers,
+ envelope.response,
+ )
+ } else {
+ (self.status_code, self.headers, self.response)
+ };
+ let headers: Option<Vec<(String, String)>> =
+ headers.map(|headers| headers.into_iter().collect());
+ let is_json = headers
+ .as_ref()
+ .and_then(|headers| {
+ headers
+ .iter()
+ .find(|(name, _)| name.eq_ignore_ascii_case("content-type"))
+ })
+ .map(|(_, value)| {
+ matches!(
+ ConnectorContentType::parse(value)
+ .as_ref()
+ .and_then(ConnectorContentType::kind),
+ Some(common_utils::request::ContentType::Json)
+ )
+ })
+ .unwrap_or(wrapped);
+ // A text body (such as XML) is kept as is; a JSON body is serialized back to bytes.
+ let body = match response {
+ Value::String(text) if !is_json => text.into_bytes(),
+ value => serde_json::to_vec(&value).map_err(|_| {
+ InjectorError::InvalidTemplate("Invalid connector response".into())
+ })?,
+ };
+ Ok(InjectorConnectorResponse {
+ status_code,
+ headers,
+ body,
+ })
+ }
}
/// Trait for converting HTTP responses to InjectorResponse
#[async_trait]
pub trait IntoInjectorResponse {
/// Convert to InjectorResponse with proper error handling
- async fn into_injector_response(
- self,
- ) -> Result<InjectorResponse, crate::injector::core::InjectorError>;
+ async fn into_injector_response(self) -> Result<InjectorResponse, InjectorError>;
}
#[async_trait]
impl IntoInjectorResponse for reqwest::Response {
- async fn into_injector_response(
- self,
- ) -> Result<InjectorResponse, crate::injector::core::InjectorError> {
+ async fn into_injector_response(self) -> Result<InjectorResponse, InjectorError> {
let status_code = self.status().as_u16();
logger::info!(
@@ -295,7 +376,7 @@ pub mod models {
let response_text = self
.text()
.await
- .map_err(|_| crate::injector::core::InjectorError::HttpRequestFailed)?;
+ .map_err(|_| InjectorError::HttpRequestFailed)?;
logger::debug!(
response_length = response_text.len(),
@@ -303,9 +384,9 @@ pub mod models {
"Processing connector response"
);
- let response_data = match serde_json::from_str::<serde_json::Value>(&response_text) {
+ let response_data = match serde_json::from_str::<Value>(&response_text) {
Ok(json) => json,
- Err(_e) => serde_json::Value::String(response_text),
+ Err(_e) => Value::String(response_text),
};
Ok(InjectorResponse {
@@ -380,6 +461,18 @@ pub mod models {
self.endpoint.host_str().unwrap_or("unknown").to_string()
}
+ /// HyperswitchVault transformation sends the template to the Hyperswitch vault proxy,
+ /// whose reply wraps the connector response in a JSON envelope.
+ pub fn uses_hyperswitch_vault_proxy(&self) -> bool {
+ matches!(
+ (&self.vault_connector_type, &self.vault_connector_id),
+ (
+ Some(VaultConnectorType::Transformation),
+ Some(VaultConnectors::HyperswitchVault)
+ )
+ )
+ }
+
/// Returns the metric-string for the vault connector, falling back to `"None"`.
pub fn vault_connector_metric_str(&self) -> &'static str {
self.vault_connector_id
diff --git a/crates/openapi/src/openapi_v2.rs b/crates/openapi/src/openapi_v2.rs
index 25528c8902..940169a99f 100644
--- a/crates/openapi/src/openapi_v2.rs
+++ b/crates/openapi/src/openapi_v2.rs
@@ -1044,6 +1044,7 @@ Never share your secret api keys. Keep them guarded and secure.
api_models::enums::ProcessTrackerStatus,
api_models::proxy::ProxyRequest,
api_models::proxy::ProxyResponse,
+ api_models::proxy::ProxyResponseBody,
api_models::proxy::TokenType,
routes::payments::ForceSync,
api_models::tokenization::GenericTokenizationRequest,
diff --git a/crates/router/Cargo.toml b/crates/router/Cargo.toml
index 77f3da0236..1961674519 100644
--- a/crates/router/Cargo.toml
+++ b/crates/router/Cargo.toml
@@ -239,6 +239,7 @@ once_cell = "1.21.3"
# HTTP requests use the shared outbound client, not OpenID Connect's bundled client.
openidconnect = { version = "3.5.0", default-features = false }
openssl = "0.10.72"
+quick-xml = "0.31.0"
rand = "0.8.5"
rand_chacha = "0.3.1"
rdkafka = "0.36.2"
@@ -251,6 +252,7 @@ reqwest = { version = "0.13.5", features = [
"multipart",
] }
ring = "0.17.14"
+roxmltree = "0.19.0"
rust_decimal = { version = "1.37.1", features = [
"serde-with-float",
"serde-with-str",
diff --git a/crates/router/src/core/proxy.rs b/crates/router/src/core/proxy.rs
index 967bf4860c..5b0c6da6bb 100644
--- a/crates/router/src/core/proxy.rs
+++ b/crates/router/src/core/proxy.rs
@@ -1,15 +1,11 @@
use super::errors::{self, RouterResponse, RouterResult};
use crate::{logger, routes::SessionState, services, types::domain};
+mod body;
pub mod utils;
use api_models::proxy as proxy_api_models;
-use common_utils::{
- ext_traits::BytesExt,
- request::{self, RequestBuilder},
-};
use error_stack::ResultExt;
use external_services::http_client::outbound_destination;
use hyperswitch_interfaces::types::Response;
-use serde_json::Value;
pub async fn proxy_core(
state: SessionState,
@@ -25,83 +21,76 @@ pub async fn proxy_core(
message: "destination_url is not valid".to_string(),
})?;
- let req_wrapper = utils::ProxyRequestWrapper(req.clone());
- let proxy_record = req_wrapper
- .get_proxy_record(&state, platform.get_provider())
- .await?;
-
- let vault_data = proxy_record.get_vault_data(&state, platform).await?;
-
- let processed_body =
- interpolate_token_references_with_vault_data(req.request_body.clone(), &vault_data)?;
+ let req_wrapper = utils::ProxyRequestWrapper(req);
+
+ let request = match req_wrapper.get_method() {
+ // GET and DELETE send no body: the token is checked, but there is nothing to validate
+ // or fill with vault data, so the request is forwarded as it is.
+ method @ (services::Method::Get | services::Method::Delete) => {
+ req_wrapper
+ .get_proxy_record(&state, platform.get_provider())
+ .await?;
+ services::RequestBuilder::new()
+ .method(method)
+ .url(req_wrapper.get_destination_url())
+ .attach_default_headers()
+ .headers(req_wrapper.get_headers())
+ .build()
+ }
+ _ => body_request(&state, platform, &req_wrapper).await?,
+ };
- let res = execute_proxy_request(&state, &req_wrapper, processed_body).await?;
+ let res = execute_proxy_request(&state, request).await?;
let proxy_response = proxy_api_models::ProxyResponse::try_from(ProxyResponseWrapper(res))?;
Ok(services::ApplicationResponse::Json(proxy_response))
}
-fn interpolate_token_references_with_vault_data(
- value: Value,
- vault_data: &Value,
-) -> RouterResult<Value> {
- match value {
- Value::Object(obj) => {
- let new_obj = obj
- .into_iter()
- .map(|(key, val)| interpolate_token_references_with_vault_data(val, vault_data).map(|processed| (key, processed)))
- .collect::<Result<serde_json::Map<_, _>, error_stack::Report<errors::ApiErrorResponse>>>()?;
-
- Ok(Value::Object(new_obj))
- }
- Value::String(s) => utils::parse_token(&s)
- .map(|(_, token_ref)| extract_field_from_vault_data(vault_data, &token_ref.field))
- .unwrap_or(Ok(Value::String(s.clone()))),
- _ => Ok(value),
- }
-}
+/// The connector request for a method with a body. The body is validated before the vault is
+/// read: reading the vault consumes the single-use CVC, so an invalid request must not reach it.
+async fn body_request(
+ state: &SessionState,
+ platform: domain::Platform,
+ req_wrapper: &utils::ProxyRequestWrapper,
+) -> RouterResult<services::Request> {
+ let content_type = req_wrapper.get_content_type()?;
+ let body = body::ProxyBody::new(req_wrapper.0.request_body.clone(), content_type.as_ref())
+ .map_err(invalid_body)?;
+ let validated_body = body
+ .builder()
+ .validate(content_type.as_ref())
+ .map_err(invalid_body)?;
-fn find_field_recursively_in_vault_data(
- obj: &serde_json::Map<String, Value>,
- field_name: &str,
-) -> Option<Value> {
- obj.get(field_name).cloned().or_else(|| {
- obj.values()
- .filter_map(|val| {
- if let Value::Object(inner_obj) = val {
- find_field_recursively_in_vault_data(inner_obj, field_name)
- } else {
- None
- }
- })
- .next()
- })
+ let proxy_record = req_wrapper
+ .get_proxy_record(state, platform.get_provider())
+ .await?;
+
+ let vault_data = proxy_record.get_vault_data(state, platform).await?;
+
+ let request = validated_body
+ .build(
+ &vault_data,
+ req_wrapper.get_destination_url(),
+ req_wrapper.get_method(),
+ req_wrapper.get_headers(),
+ )
+ .map_err(invalid_body)?
+ .into_inner();
+ Ok(request)
}
-fn extract_field_from_vault_data(vault_data: &Value, field_name: &str) -> RouterResult<Value> {
- match vault_data {
- Value::Object(obj) => find_field_recursively_in_vault_data(obj, field_name)
- .ok_or_else(|| errors::ApiErrorResponse::InternalServerError)
- .attach_printable(format!("Field '{field_name}' not found")),
- _ => Err(errors::ApiErrorResponse::InternalServerError)
- .attach_printable("Vault data is not a valid JSON object"),
+/// A connector body that cannot be sent is a client error.
+fn invalid_body(error: body::ProxyBodyError) -> errors::ApiErrorResponse {
+ errors::ApiErrorResponse::InvalidRequestData {
+ message: error.to_string(),
}
}
async fn execute_proxy_request(
state: &SessionState,
- req_wrapper: &utils::ProxyRequestWrapper,
- processed_body: Value,
+ request: services::Request,
) -> RouterResult<Response> {
- let request = RequestBuilder::new()
- .method(req_wrapper.get_method())
- .attach_default_headers()
- .headers(req_wrapper.get_headers())
- .url(req_wrapper.get_destination_url())
- .set_body(request::RequestContent::Json(Box::new(processed_body)))
- .build();
-
let response = services::call_connector_api(state, request, "proxy", None)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
@@ -126,19 +115,23 @@ impl TryFrom<ProxyResponseWrapper> for proxy_api_models::ProxyResponse {
fn try_from(wrapper: ProxyResponseWrapper) -> Result<Self, Self::Error> {
let res = wrapper.0;
- let response_body: Value = res
- .response
- .parse_struct("ProxyResponse")
- .change_context(errors::ApiErrorResponse::InternalServerError)
- .attach_printable("Failed to parse the response")?;
-
- let status_code = res.status_code;
- let response_headers = proxy_api_models::Headers::from_header_map(res.headers.as_ref());
-
Ok(Self {
- response: response_body,
- status_code,
- response_headers,
+ response: response_body(&res.response)?,
+ status_code: res.status_code,
+ response_headers: proxy_api_models::Headers::from_header_map(res.headers.as_ref()),
})
}
}
+
+/// The connector body as JSON, else as text. Only UTF-8 text is supported; other encodings
+/// are rejected rather than converted lossily.
+fn response_body(body: &[u8]) -> RouterResult<proxy_api_models::ProxyResponseBody> {
+ serde_json::from_slice(body)
+ .map(proxy_api_models::ProxyResponseBody::Json)
+ .or_else(|_| {
+ std::str::from_utf8(body)
+ .map(|text| proxy_api_models::ProxyResponseBody::Text(text.to_owned()))
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Connector response is neither JSON nor UTF-8 text")
+ })
+}
diff --git a/crates/router/src/core/proxy/body.rs b/crates/router/src/core/proxy/body.rs
new file mode 100644
index 0000000000..ca6373a283
--- /dev/null
+++ b/crates/router/src/core/proxy/body.rs
@@ -0,0 +1,178 @@
+//! Format-aware connector body interpolation for the vault proxy.
+
+use common_utils::request::{
+ ConnectorContentType, ContentType, Method, Request, RequestBuilder, RequestContent,
+};
+use serde_json::Value;
+
+mod json;
+mod placeholder;
+mod xml;
+
+/// The connector body of a proxy request.
+#[derive(Debug)]
+pub enum ProxyBody {
+ /// A JSON body.
+ Json(Value),
+ /// A complete, UTF-8 XML/SOAP document.
+ Xml(String),
+}
+
+/// Errors omit template and resolved field contents.
+#[derive(Debug, thiserror::Error)]
+pub enum ProxyBodyError {
+ /// A placeholder is syntactically invalid.
+ #[error("Malformed vault placeholder")]
+ InvalidPlaceholder,
+ /// The referenced field does not exist or cannot be used as a scalar.
+ #[error("Missing or non-scalar vault field: {0}")]
+ InvalidField(String),
+ /// The Content-Type is neither JSON nor XML.
+ #[error("Unsupported connector Content-Type; only JSON and XML are supported")]
+ UnsupportedContentType,
+ /// An XML Content-Type with a non-UTF-8 charset, or with a body that is not a string.
+ #[error("Connector body does not match its Content-Type")]
+ InvalidContentType,
+ /// An XML document or its template placement is invalid.
+ #[error("Invalid XML template")]
+ InvalidXml,
+ /// Serialization failed.
+ #[error("Failed to serialize connector body")]
+ Serialization,
+}
+
+impl ProxyBody {
+ /// The connector body for the declared Content-Type: JSON, also when none is declared,
+ /// or a UTF-8 XML document sent as a string. Any other Content-Type is rejected.
+ pub fn new(
+ request_body: Value,
+ content_type: Option<&ConnectorContentType<'_>>,
+ ) -> Result<Self, ProxyBodyError> {
+ let kind = content_type.map_or(Some(ContentType::Json), ConnectorContentType::kind);
+ match (kind, request_body) {
+ (Some(ContentType::Json), body) => Ok(Self::Json(body)),
+ (Some(ContentType::Xml), Value::String(xml))
+ if content_type.is_some_and(ConnectorContentType::is_utf8) =>
+ {
+ Ok(Self::Xml(xml))
+ }
+ (Some(ContentType::Xml), _) => Err(ProxyBodyError::InvalidContentType),
+ _ => Err(ProxyBodyError::UnsupportedContentType),
+ }
+ }
+
+ /// Content-Type sent when the caller does not declare one.
+ fn default_content_type(&self) -> &'static str {
+ match self {
+ Self::Json(_) => "application/json",
+ Self::Xml(_) => "application/xml",
+ }
+ }
+
+ /// Check the body's structure and placeholder syntax, without vault data.
+ fn validate(&self) -> Result<(), ProxyBodyError> {
+ match self {
+ Self::Json(body) => json::validate(body),
+ Self::Xml(template) => xml::validate(template),
+ }
+ }
+
+ /// Replace placeholders with vault values and produce the connector bytes.
+ fn render(&self, vault: &Value) -> Result<Vec<u8>, ProxyBodyError> {
+ match self {
+ Self::Json(body) => json::render(body, vault),
+ Self::Xml(template) => xml::render(template, vault),
+ }
+ }
+
+ /// Start turning this body into a connector request. See [`ProxyBodyBuilder`].
+ pub fn builder(&self) -> ProxyBodyBuilder<'_, Init> {
+ ProxyBodyBuilder {
+ body: self,
+ state: Init,
+ }
+ }
+}
+
+/// Type-state builder that turns a [`ProxyBody`] into a connector request:
+/// [`Init`] → [`Validated`] → [`Prepared`]. Validation checks the whole body without vault
+/// data, so an invalid request never reaches the vault.
+#[derive(Debug)]
+pub struct ProxyBodyBuilder<'a, S> {
+ body: &'a ProxyBody,
+ state: S,
+}
+
+/// Builder state before validation.
+#[derive(Debug)]
+pub struct Init;
+
+/// Builder state after the body passed validation.
+#[derive(Debug)]
+pub struct Validated<'a> {
+ content_type: Option<&'a ConnectorContentType<'a>>,
+}
+
+/// Builder state holding the prepared request, ready to be sent to the connector.
+#[derive(Debug)]
+pub struct Prepared(Request);
+
+impl<'a> ProxyBodyBuilder<'a, Init> {
+ /// Check the body without vault data: its structure and placeholder syntax.
+ pub fn validate(
+ self,
+ content_type: Option<&'a ConnectorContentType<'a>>,
+ ) -> Result<ProxyBodyBuilder<'a, Validated<'a>>, ProxyBodyError> {
+ self.body.validate()?;
+ Ok(ProxyBodyBuilder {
+ body: self.body,
+ state: Validated { content_type },
+ })
+ }
+}
+
+impl<'a> ProxyBodyBuilder<'a, Validated<'a>> {
+ /// Resolve placeholders from vault data and build the connector request. The caller's
+ /// Content-Type, Content-Length and Transfer-Encoding headers are dropped, as interpolation
+ /// changes the body length; the declared Content-Type, or the body's default, is set again.
+ pub fn build(
+ self,
+ vault: &Value,
+ url: &str,
+ method: Method,
+ headers: Vec<(String, hyperswitch_masking::Maskable<String>)>,
+ ) -> Result<ProxyBodyBuilder<'a, Prepared>, ProxyBodyError> {
+ let bytes = self.body.render(vault)?;
+ let content_type = self.state.content_type.map_or(
+ self.body.default_content_type(),
+ ConnectorContentType::header,
+ );
+ let headers = headers
+ .into_iter()
+ .filter(|(name, _)| {
+ !["content-type", "content-length", "transfer-encoding"]
+ .iter()
+ .any(|blocked| name.eq_ignore_ascii_case(blocked))
+ })
+ .chain([("Content-Type".to_owned(), content_type.to_owned().into())])
+ .collect();
+ let request = RequestBuilder::new()
+ .method(method)
+ .url(url)
+ .attach_default_headers()
+ .headers(headers)
+ .set_body(RequestContent::RawBytes(bytes))
+ .build();
+ Ok(ProxyBodyBuilder {
+ body: self.body,
+ state: Prepared(request),
+ })
+ }
+}
+
+impl ProxyBodyBuilder<'_, Prepared> {
+ /// The prepared request, to be sent to the connector.
+ pub fn into_inner(self) -> Request {
+ self.state.0
+ }
+}
diff --git a/crates/router/src/core/proxy/body/json.rs b/crates/router/src/core/proxy/body/json.rs
new file mode 100644
index 0000000000..453853a60c
--- /dev/null
+++ b/crates/router/src/core/proxy/body/json.rs
@@ -0,0 +1,45 @@
+//! JSON bodies: placeholders are resolved inside string values, and a placeholder that is a
+//! whole value keeps the vault value's JSON type.
+
+use serde_json::Value;
+
+use super::{
+ placeholder::{parse_placeholder, substitute, validate_placeholders, value},
+ ProxyBodyError,
+};
+
+/// Check placeholder syntax in every string value.
+pub(super) fn validate(item: &Value) -> Result<(), ProxyBodyError> {
+ match item {
+ Value::String(text) => validate_placeholders(text),
+ Value::Array(items) => items.iter().try_for_each(validate),
+ Value::Object(fields) => fields.values().try_for_each(validate),
+ _ => Ok(()),
+ }
+}
+
+/// The JSON bytes with placeholders replaced by vault values.
+pub(super) fn render(body: &Value, vault: &Value) -> Result<Vec<u8>, ProxyBodyError> {
+ serde_json::to_vec(&resolve(body, vault)?).map_err(|_| ProxyBodyError::Serialization)
+}
+
+/// Resolve placeholders in string values; object keys are never interpolated.
+fn resolve(item: &Value, vault: &Value) -> Result<Value, ProxyBodyError> {
+ match item {
+ Value::String(text) => match parse_placeholder(text)? {
+ Some((field, consumed)) if consumed == text.len() => value(vault, field),
+ _ => substitute(text, vault, str::to_owned).map(Value::String),
+ },
+ Value::Array(items) => items
+ .iter()
+ .map(|item| resolve(item, vault))
+ .collect::<Result<_, _>>()
+ .map(Value::Array),
+ Value::Object(fields) => fields
+ .iter()
+ .map(|(key, item)| resolve(item, vault).map(|item| (key.clone(), item)))
+ .collect::<Result<_, _>>()
+ .map(Value::Object),
+ other => Ok(other.clone()),
+ }
+}
diff --git a/crates/router/src/core/proxy/body/placeholder.rs b/crates/router/src/core/proxy/body/placeholder.rs
new file mode 100644
index 0000000000..309001ed4f
--- /dev/null
+++ b/crates/router/src/core/proxy/body/placeholder.rs
@@ -0,0 +1,102 @@
+//! `{{$field}}` placeholder parsing and vault field lookup, shared by every body format.
+
+use common_utils::fp_utils::when;
+use serde_json::Value;
+
+use super::ProxyBodyError;
+
+/// Depth-first lookup of a vault field by name, through nested objects and arrays.
+pub fn find_field<'a>(vault: &'a Value, field: &str) -> Option<&'a Value> {
+ match vault {
+ Value::Object(map) => map
+ .get(field)
+ .or_else(|| map.values().find_map(|v| find_field(v, field))),
+ Value::Array(values) => values.iter().find_map(|v| find_field(v, field)),
+ _ => None,
+ }
+}
+
+/// The value of a placeholder embedded in text.
+fn scalar(vault: &Value, field: &str) -> Result<String, ProxyBodyError> {
+ match find_field(vault, field) {
+ Some(Value::String(s)) => Ok(s.clone()),
+ Some(Value::Number(n)) => Ok(n.to_string()),
+ Some(Value::Bool(b)) => Ok(b.to_string()),
+ _ => Err(ProxyBodyError::InvalidField(field.to_owned())),
+ }
+}
+
+/// The value of a placeholder that is a whole JSON value, keeping its JSON type.
+pub(super) fn value(vault: &Value, field: &str) -> Result<Value, ProxyBodyError> {
+ find_field(vault, field)
+ .cloned()
+ .ok_or_else(|| ProxyBodyError::InvalidField(field.to_owned()))
+}
+
+/// Parse a `{{$field}}` placeholder at the start of `input`.
+///
+/// Returns the field name and the number of bytes consumed, `None` when `input` does not
+/// start with a placeholder, and an error for a malformed one such as `{{$}}`.
+pub fn parse_placeholder(input: &str) -> Result<Option<(&str, usize)>, ProxyBodyError> {
+ input
+ .strip_prefix("{{")
+ .filter(|rest| rest.trim_start().starts_with('$'))
+ .map(|rest| -> Result<_, ProxyBodyError> {
+ let end = rest.find("}}").ok_or(ProxyBodyError::InvalidPlaceholder)?;
+ let field = rest[..end]
+ .trim()
+ .strip_prefix('$')
+ .ok_or(ProxyBodyError::InvalidPlaceholder)?;
+ when(
+ field.is_empty() || !field.chars().all(|c| c.is_ascii_alphanumeric() || c == '_'),
+ || Err(ProxyBodyError::InvalidPlaceholder),
+ )?;
+ Ok((field, end + 4))
+ })
+ .transpose()
+}
+
+/// Replace every placeholder in `template` with its scalar vault value, escaped for
+/// the surrounding format.
+pub(super) fn substitute(
+ template: &str,
+ vault: &Value,
+ escape: impl Fn(&str) -> String,
+) -> Result<String, ProxyBodyError> {
+ let mut output = String::with_capacity(template.len());
+ let mut rest = template;
+ while let Some(start) = rest.find("{{") {
+ output.push_str(&rest[..start]);
+ rest = &rest[start..];
+ match parse_placeholder(rest)? {
+ Some((field, consumed)) => {
+ output.push_str(&escape(&scalar(vault, field)?));
+ rest = &rest[consumed..];
+ }
+ // Not a placeholder: keep the `{{` as text.
+ None => {
+ output.push_str("{{");
+ rest = &rest[2..];
+ }
+ }
+ }
+ output.push_str(rest);
+ Ok(output)
+}
+
+/// Check the syntax of every placeholder in `template`.
+pub(super) fn validate_placeholders(template: &str) -> Result<(), ProxyBodyError> {
+ template
+ .match_indices("{{")
+ .try_for_each(|(start, _)| parse_placeholder(&template[start..]).map(|_| ()))
+}
+
+/// Whether `template` contains at least one placeholder.
+pub(super) fn has_reference(template: &str) -> Result<bool, ProxyBodyError> {
+ // The first valid or malformed placeholder decides; other `{{` text is skipped.
+ template
+ .match_indices("{{")
+ .find_map(|(start, _)| parse_placeholder(&template[start..]).transpose())
+ .transpose()
+ .map(|placeholder| placeholder.is_some())
+}
diff --git a/crates/router/src/core/proxy/body/xml.rs b/crates/router/src/core/proxy/body/xml.rs
new file mode 100644
index 0000000000..fd1c129334
--- /dev/null
+++ b/crates/router/src/core/proxy/body/xml.rs
@@ -0,0 +1,112 @@
+//! XML and SOAP bodies: `quick_xml` reads and writes the document, and placeholders are
+//! resolved in text, attribute values and CDATA.
+
+use common_utils::{fp_utils::when, request::is_utf8_label};
+use quick_xml::{
+ escape::escape,
+ events::{BytesCData, BytesStart, BytesText, Event},
+ Reader, Writer,
+};
+use roxmltree::{Document, ParsingOptions};
+use serde_json::Value;
+
+use super::{
+ placeholder::{has_reference, substitute, validate_placeholders},
+ ProxyBodyError,
+};
+
+/// Characters allowed in an XML 1.0 document.
+fn valid_chars(value: &str) -> bool {
+ value.chars().all(|c| {
+ matches!(c, '\t' | '\r' | '\n')
+ || ('\u{20}'..='\u{d7ff}').contains(&c)
+ || ('\u{e000}'..='\u{fffd}').contains(&c)
+ || ('\u{10000}'..='\u{10ffff}').contains(&c)
+ })
+}
+
+/// The raw bytes of an event as text.
+fn as_text(bytes: &[u8]) -> Result<&str, ProxyBodyError> {
+ std::str::from_utf8(bytes).map_err(|_| ProxyBodyError::InvalidXml)
+}
+
+/// Check that the template is well-formed UTF-8 XML whose placeholders are valid and sit in
+/// text or attribute values only. Being well-formed keeps them out of element and attribute
+/// names, as `{` is not allowed in a name.
+pub(super) fn validate(template: &str) -> Result<(), ProxyBodyError> {
+ let invalid = || Err(ProxyBodyError::InvalidXml);
+ validate_placeholders(template)?;
+ let options = ParsingOptions {
+ allow_dtd: true,
+ nodes_limit: 10_000,
+ };
+ let document =
+ Document::parse_with_options(template, options).map_err(|_| ProxyBodyError::InvalidXml)?;
+ // Token references in the declaration and DTD (before the root element), comments and
+ // processing instructions are not card data positions.
+ let prolog = template
+ .get(..document.root_element().range().start)
+ .unwrap_or_default();
+ let comments = document.descendants().filter_map(|node| {
+ if node.is_comment() {
+ node.text()
+ } else {
+ node.pi().and_then(|pi| pi.value)
+ }
+ });
+ std::iter::once(prolog)
+ .chain(comments)
+ .try_for_each(|text| when(has_reference(text)?, invalid))?;
+ when(!declares_utf8(template), invalid)
+}
+
+/// Whether the XML declaration, if any, names UTF-8, the encoding the template is sent in.
+/// `roxmltree` does not check the declared encoding.
+fn declares_utf8(template: &str) -> bool {
+ match Reader::from_str(template).read_event() {
+ Ok(Event::Decl(declaration)) => declaration
+ .encoding()
+ .is_none_or(|encoding| encoding.is_ok_and(|encoding| is_utf8_label(&encoding))),
+ _ => true,
+ }
+}
+
+/// Replace placeholders with escaped vault values. The template has passed [`validate`],
+/// so placeholders appear only in text, attribute values and CDATA.
+pub(super) fn render(template: &str, vault: &Value) -> Result<Vec<u8>, ProxyBodyError> {
+ let fill = |raw: &str| substitute(raw, vault, |value| escape(value).into_owned());
+ let mut reader = Reader::from_str(template);
+ let mut writer = Writer::new(Vec::with_capacity(template.len()));
+ loop {
+ let event = match reader
+ .read_event()
+ .map_err(|_| ProxyBodyError::InvalidXml)?
+ {
+ Event::Eof => break,
+ Event::Start(element) => Event::Start(BytesStart::from_content(
+ fill(as_text(&element)?)?,
+ element.name().as_ref().len(),
+ )),
+ Event::Empty(element) => Event::Empty(BytesStart::from_content(
+ fill(as_text(&element)?)?,
+ element.name().as_ref().len(),
+ )),
+ Event::Text(text) => Event::Text(BytesText::from_escaped(fill(as_text(&text)?)?)),
+ // A CDATA section cannot contain `]]>`, so a value holding it is split across two.
+ Event::CData(data) => Event::CData(BytesCData::new(substitute(
+ as_text(&data)?,
+ vault,
+ |value| value.replace("]]>", "]]]]><![CDATA[>"),
+ )?)),
+ other => other,
+ };
+ writer
+ .write_event(event)
+ .map_err(|_| ProxyBodyError::InvalidXml)?;
+ }
+ let output = writer.into_inner();
+ when(!valid_chars(as_text(&output)?), || {
+ Err(ProxyBodyError::InvalidXml)
+ })?;
+ Ok(output)
+}
diff --git a/crates/router/src/core/proxy/utils.rs b/crates/router/src/core/proxy/utils.rs
index e6615773df..059016a496 100644
--- a/crates/router/src/core/proxy/utils.rs
+++ b/crates/router/src/core/proxy/utils.rs
@@ -3,6 +3,7 @@ use common_utils::{
crypto::{DecodeMessage, GcmAes256},
encryption::Encryption,
ext_traits::{BytesExt, Encode, OptionExt},
+ fp_utils::when,
id_type,
};
use error_stack::ResultExt;
@@ -10,12 +11,6 @@ use hyperswitch_domain_models::payment_methods;
use hyperswitch_masking::{Mask, PeekInterface};
use serde_json::Value;
use storage_impl::behaviour::Conversion;
-use x509_parser::nom::{
- bytes::complete::{tag, take_while1},
- character::complete::{char, multispace0},
- sequence::{delimited, preceded, terminated},
- IResult,
-};
use crate::{
core::{
@@ -178,6 +173,38 @@ impl ProxyRequestWrapper {
.collect()
}
+ /// The connector Content-Type, parsed once for the whole proxy flow. Header names are
+ /// case-insensitive. An invalid Content-Type is rejected, and so are conflicting
+ /// duplicates, instead of picking one of them from the HashMap.
+ pub fn get_content_type(
+ &self,
+ ) -> RouterResult<Option<common_utils::request::ConnectorContentType<'_>>> {
+ let values: Vec<&str> = self
+ .0
+ .headers
+ .as_map()
+ .iter()
+ .filter(|(name, _)| name.eq_ignore_ascii_case("content-type"))
+ .map(|(_, value)| value.as_str())
+ .collect();
+ let first = values.first().copied();
+ when(values.iter().any(|value| Some(*value) != first), || {
+ Err(errors::ApiErrorResponse::InvalidRequestData {
+ message: "Conflicting connector Content-Type headers".into(),
+ })
+ })?;
+ first
+ .map(|value| {
+ common_utils::request::ConnectorContentType::parse(value).ok_or_else(|| {
+ errors::ApiErrorResponse::InvalidRequestData {
+ message: "Invalid connector Content-Type header".into(),
+ }
+ .into()
+ })
+ })
+ .transpose()
+ }
+
pub fn get_destination_url(&self) -> &str {
self.0.destination_url.get_string_repr()
}
@@ -390,35 +417,6 @@ impl ProxyRecord {
}
}
-#[derive(Debug)]
-pub struct TokenReference {
- pub field: String,
-}
-
-pub fn parse_token(input: &str) -> IResult<&str, TokenReference> {
- let (input, field) = delimited(
- tag("{{"),
- preceded(
- multispace0,
- preceded(
- char('$'),
- terminated(
- take_while1(|c: char| c.is_alphanumeric() || c == '_'),
- multispace0,
- ),
- ),
- ),
- tag("}}"),
- )(input)?;
-
- Ok((
- input,
- TokenReference {
- field: field.to_string(),
- },
- ))
-}
-
pub fn contains_token(s: &str) -> bool {
s.contains("{{") && s.contains("$") && s.contains("}}")
}