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(injector): Fix injector core flow (#11784)

Prasunna Soppa7683595ef988
diff --git a/Cargo.lock b/Cargo.lock
index cbf6d738c7..584450b7e7 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -2232,7 +2232,7 @@ dependencies = [
[[package]]
name = "config_patch_derive"
version = "0.1.0"
-source = "git+https://github.com/juspay/connector-service?rev=71fcc81f627c63c4cdc42a8d55eb73f257e3b4c5#71fcc81f627c63c4cdc42a8d55eb73f257e3b4c5"
+source = "git+https://github.com/juspay/connector-service?rev=2dcbcf76ff0411d8718172ab9e30c5be9688349e#2dcbcf76ff0411d8718172ab9e30c5be9688349e"
dependencies = [
"proc-macro2",
"quote",
@@ -3947,7 +3947,7 @@ checksum = "32619942b8be646939eaf3db0602b39f5229b74575b67efc897811ded1db4e57"
[[package]]
name = "grpc-api-types"
version = "0.1.0"
-source = "git+https://github.com/juspay/connector-service?rev=71fcc81f627c63c4cdc42a8d55eb73f257e3b4c5#71fcc81f627c63c4cdc42a8d55eb73f257e3b4c5"
+source = "git+https://github.com/juspay/connector-service?rev=2dcbcf76ff0411d8718172ab9e30c5be9688349e#2dcbcf76ff0411d8718172ab9e30c5be9688349e"
dependencies = [
"axum 0.8.4",
"error-stack 0.5.0",
@@ -8115,7 +8115,7 @@ dependencies = [
[[package]]
name = "rust-grpc-client"
version = "0.1.0"
-source = "git+https://github.com/juspay/connector-service?rev=71fcc81f627c63c4cdc42a8d55eb73f257e3b4c5#71fcc81f627c63c4cdc42a8d55eb73f257e3b4c5"
+source = "git+https://github.com/juspay/connector-service?rev=2dcbcf76ff0411d8718172ab9e30c5be9688349e#2dcbcf76ff0411d8718172ab9e30c5be9688349e"
dependencies = [
"grpc-api-types",
]
@@ -10943,7 +10943,7 @@ checksum = "ed646292ffc8188ef8ea4d1e0e0150fb15a5c2e12ad9b8fc191ae7a8a7f3c4b9"
[[package]]
name = "ucs_cards"
version = "0.1.0"
-source = "git+https://github.com/juspay/connector-service?rev=71fcc81f627c63c4cdc42a8d55eb73f257e3b4c5#71fcc81f627c63c4cdc42a8d55eb73f257e3b4c5"
+source = "git+https://github.com/juspay/connector-service?rev=2dcbcf76ff0411d8718172ab9e30c5be9688349e#2dcbcf76ff0411d8718172ab9e30c5be9688349e"
dependencies = [
"bytes 1.10.1",
"error-stack 0.4.1",
@@ -10959,7 +10959,7 @@ dependencies = [
[[package]]
name = "ucs_common_enums"
version = "0.1.0"
-source = "git+https://github.com/juspay/connector-service?rev=71fcc81f627c63c4cdc42a8d55eb73f257e3b4c5#71fcc81f627c63c4cdc42a8d55eb73f257e3b4c5"
+source = "git+https://github.com/juspay/connector-service?rev=2dcbcf76ff0411d8718172ab9e30c5be9688349e#2dcbcf76ff0411d8718172ab9e30c5be9688349e"
dependencies = [
"serde",
"strum 0.26.3",
@@ -10970,7 +10970,7 @@ dependencies = [
[[package]]
name = "ucs_common_utils"
version = "0.1.0"
-source = "git+https://github.com/juspay/connector-service?rev=71fcc81f627c63c4cdc42a8d55eb73f257e3b4c5#71fcc81f627c63c4cdc42a8d55eb73f257e3b4c5"
+source = "git+https://github.com/juspay/connector-service?rev=2dcbcf76ff0411d8718172ab9e30c5be9688349e#2dcbcf76ff0411d8718172ab9e30c5be9688349e"
dependencies = [
"anyhow",
"base64 0.21.7",
diff --git a/crates/api_models/src/enums.rs b/crates/api_models/src/enums.rs
index 86f044d906..1deab67296 100644
--- a/crates/api_models/src/enums.rs
+++ b/crates/api_models/src/enums.rs
@@ -220,7 +220,9 @@ pub enum BillingConnectors {
DummyBillingConnector,
}
-#[derive(Clone, Copy, Debug, serde::Serialize, strum::EnumString, Eq, PartialEq)]
+#[derive(
+ Clone, Copy, Debug, serde::Serialize, serde::Deserialize, strum::EnumString, Eq, PartialEq,
+)]
#[serde(rename_all = "snake_case")]
#[strum(serialize_all = "snake_case")]
pub enum VaultConnectors {
diff --git a/crates/external_services/Cargo.toml b/crates/external_services/Cargo.toml
index ee55729cb3..5bc8112a3f 100644
--- a/crates/external_services/Cargo.toml
+++ b/crates/external_services/Cargo.toml
@@ -73,7 +73,7 @@ reqwest = { version = "0.11.27", features = ["rustls-tls"] }
http = "0.2.12"
url = { version = "2.5.4", features = ["serde"] }
quick-xml = { version = "0.31.0", features = ["serialize"] }
-unified-connector-service-client = { git = "https://github.com/juspay/connector-service", rev = "71fcc81f627c63c4cdc42a8d55eb73f257e3b4c5", package = "rust-grpc-client" }
+unified-connector-service-client = { git = "https://github.com/juspay/connector-service", rev = "2dcbcf76ff0411d8718172ab9e30c5be9688349e", package = "rust-grpc-client" }
open-feature = { version = "0.2.5", optional = true }
superposition_provider = { version = "0.102.0", optional = true}
superposition_types = "0.102.0"
diff --git a/crates/external_services/src/grpc_client/unified_connector_service.rs b/crates/external_services/src/grpc_client/unified_connector_service.rs
index 6dcc35b8d6..04f7f27337 100644
--- a/crates/external_services/src/grpc_client/unified_connector_service.rs
+++ b/crates/external_services/src/grpc_client/unified_connector_service.rs
@@ -98,12 +98,53 @@ pub struct ConnectorAuthMetadata {
pub connector_config: Option<Secret<String>>,
}
+/// Type of the vault connector
+#[derive(Debug, Clone, serde::Deserialize, serde::Serialize)]
+#[serde(rename_all = "snake_case")]
+pub enum VaultConnectorType {
+ /// Proxy vault - forwards requests through a proxy (e.g., VGS forward proxy)
+ Proxy,
+ /// Transformation vault - transforms/tokenizes data (e.g., HyperswitchVault)
+ Transformation,
+}
+
+/// Authentication credentials for vault connectors
+#[derive(Debug, Clone, serde::Deserialize, serde::Serialize)]
+pub struct VaultConnectorAuth {
+ /// API key for authenticating with the vault connector
+ pub api_key: Secret<String>,
+ /// API secret for authenticating with the vault connector
+ pub profile_id: Secret<String>,
+}
+
/// External Vault Proxy Related Metadata
#[derive(Debug, Clone, serde::Deserialize, serde::Serialize)]
#[serde(untagged)]
pub enum ExternalVaultProxyMetadata {
/// VGS proxy data variant
VgsMetadata(VgsMetadata),
+ /// HyperswitchVault data variant
+ HyperswitchVaultMetadata(HyperswitchVaultMetadata),
+}
+
+/// Complete external vault proxy configuration to be serialized and sent to UCS
+#[derive(Debug, Clone, serde::Deserialize, serde::Serialize)]
+pub struct ExternalVaultProxyConfig {
+ /// Type of the vault connector (e.g., Proxy or Transformation)
+ pub vault_connector_type: VaultConnectorType,
+ /// Name/ID of the vault connector (e.g., "vgs", "hyperswitch_vault")
+ pub vault_connector_id: Option<String>,
+ /// Metadata specific to the vault connector type
+ pub metadata: ExternalVaultProxyMetadata,
+}
+
+/// HyperswitchVault proxy data
+#[derive(Debug, Clone, serde::Deserialize, serde::Serialize)]
+pub struct HyperswitchVaultMetadata {
+ /// External vault url
+ pub vault_endpoint: Url,
+ /// Authentication data for the vault connector
+ pub vault_auth_data: VaultConnectorAuth,
}
/// Builds a gRPC client with timeout handling
diff --git a/crates/hyperswitch_interfaces/Cargo.toml b/crates/hyperswitch_interfaces/Cargo.toml
index c2c9db3a2c..0306e3fe8f 100644
--- a/crates/hyperswitch_interfaces/Cargo.toml
+++ b/crates/hyperswitch_interfaces/Cargo.toml
@@ -30,7 +30,7 @@ strum = { version = "0.26", features = ["derive"] }
thiserror = "1.0.69"
time = "0.3.41"
url = { version = "2.5.4", features = ["serde"] }
-unified-connector-service-client = { git = "https://github.com/juspay/connector-service", rev = "71fcc81f627c63c4cdc42a8d55eb73f257e3b4c5", package = "rust-grpc-client" }
+unified-connector-service-client = { git = "https://github.com/juspay/connector-service", rev = "2dcbcf76ff0411d8718172ab9e30c5be9688349e", package = "rust-grpc-client" }
tokio = { version = "1.45.1", features = ["macros", "rt-multi-thread"] }
# First party crates
diff --git a/crates/hyperswitch_interfaces/src/unified_connector_service/transformers.rs b/crates/hyperswitch_interfaces/src/unified_connector_service/transformers.rs
index ef195b5481..efd41dbcb9 100644
--- a/crates/hyperswitch_interfaces/src/unified_connector_service/transformers.rs
+++ b/crates/hyperswitch_interfaces/src/unified_connector_service/transformers.rs
@@ -675,6 +675,22 @@ impl ForeignTryFrom<payments_grpc::BankType> for common_enums::BankType {
UnifiedConnectorServiceError::ResponseDeserializationFailed,
)
.attach_printable("BankType unspecified")),
+ payments_grpc::BankType::Transmission => Err(error_stack::Report::new(
+ UnifiedConnectorServiceError::ResponseDeserializationFailed,
+ )
+ .attach_printable("BankType unspecified")),
+ payments_grpc::BankType::Current => Err(error_stack::Report::new(
+ UnifiedConnectorServiceError::ResponseDeserializationFailed,
+ )
+ .attach_printable("BankType unspecified")),
+ payments_grpc::BankType::Bond => Err(error_stack::Report::new(
+ UnifiedConnectorServiceError::ResponseDeserializationFailed,
+ )
+ .attach_printable("BankType unspecified")),
+ payments_grpc::BankType::SubscriptionShare => Err(error_stack::Report::new(
+ UnifiedConnectorServiceError::ResponseDeserializationFailed,
+ )
+ .attach_printable("BankType unspecified")),
}
}
}
diff --git a/crates/injector/src/injector.rs b/crates/injector/src/injector.rs
index 5990232ccb..ae13f4b5e0 100644
--- a/crates/injector/src/injector.rs
+++ b/crates/injector/src/injector.rs
@@ -11,7 +11,7 @@ pub mod core {
sequence::{delimited, preceded, terminated},
IResult,
};
- use router_env::{instrument, logger, tracing};
+ use router_env::{instrument, logger};
use serde_json::Value;
use thiserror::Error;
@@ -59,7 +59,29 @@ pub mod core {
}
}
- /// Create HTTP client using the proven external_services create_client logic
+ impl Proxy {
+ /// Builds a `Proxy` from an optional proxy URL secret, applying it to both HTTP and
+ /// HTTPS slots. Returns `Proxy::default()` when `proxy_url` is `None`.
+ fn from_optional_url(proxy_url: Option<hyperswitch_masking::Secret<String>>) -> Self {
+ match proxy_url {
+ Some(url) => {
+ let url_str = url.expose();
+ Self {
+ http_url: Some(url_str.clone()),
+ https_url: Some(url_str),
+ idle_pool_connection_timeout: Some(90),
+ bypass_proxy_hosts: None,
+ }
+ }
+ None => Self::default(),
+ }
+ }
+ }
+
+ // ---------------------------------------------------------------------------
+ // TLS / HTTP client helpers
+ // ---------------------------------------------------------------------------
+
fn create_client(
proxy_config: &Proxy,
client_certificate: Option<hyperswitch_masking::Secret<String>>,
@@ -73,26 +95,23 @@ pub mod core {
"Creating HTTP client"
);
- // Case 1: Mutual TLS with client certificate and key
+ // Case 1: Mutual TLS
if let (Some(encoded_certificate), Some(encoded_certificate_key)) =
(client_certificate.clone(), client_certificate_key.clone())
{
if ca_certificate.is_some() {
logger::warn!("All of client certificate, client key, and CA certificate are provided. CA certificate will be ignored in mutual TLS setup.");
}
-
let client_builder = get_client_builder(proxy_config)?;
-
let identity = create_identity_from_certificate_and_key(
encoded_certificate.clone(),
encoded_certificate_key,
)?;
-
let certificate_list = create_certificate(encoded_certificate)?;
let client_builder = certificate_list
.into_iter()
- .fold(client_builder, |client_builder, certificate| {
- client_builder.add_root_certificate(certificate)
+ .fold(client_builder, |client, cert| {
+ client.add_root_certificate(cert)
});
return client_builder
.identity(identity)
@@ -107,9 +126,9 @@ pub mod core {
});
}
- // Case 2: Use provided CA certificate for server authentication only (one-way TLS)
+ // Case 2: One-way TLS with CA cert
if let Some(ca_pem) = ca_certificate {
- let pem = ca_pem.expose().replace("\\r\\n", "\n"); // Fix escaped newlines
+ let pem = ca_pem.expose().replace("\\r\\n", "\n");
let cert = reqwest::Certificate::from_pem(pem.as_bytes())
.change_context(InjectorError::HttpRequestFailed)
.inspect_err(|e| {
@@ -125,48 +144,60 @@ pub mod core {
});
}
- // Case 3: Default client (no certs)
- get_base_client(proxy_config)
+ // Case 3: Default (no certs)
+ get_client_builder(proxy_config)?
+ .build()
+ .change_context(InjectorError::HttpRequestFailed)
+ .inspect_err(|e| logger::error!("Failed to build default HTTP client: {:?}", e))
+ }
+
+ /// Extracts vault proxy URL and CA cert from headers when the vault-metadata header is present.
+ /// Returns `(proxy_url, ca_cert)` — both `None` when the header is absent or extraction fails.
+ fn extract_vault_metadata(
+ headers: &HashMap<String, hyperswitch_masking::Secret<String>>,
+ endpoint: url::Url,
+ http_method: injector_types::HttpMethod,
+ ) -> (
+ Option<hyperswitch_masking::Secret<String>>,
+ Option<hyperswitch_masking::Secret<String>>,
+ ) {
+ if !headers.contains_key(crate::consts::EXTERNAL_VAULT_METADATA_HEADER) {
+ return (None, None);
+ }
+ let mut temp_config = injector_types::ConnectionConfig::new(endpoint, http_method);
+ if temp_config.extract_and_apply_vault_metadata_with_fallback(headers) {
+ (temp_config.proxy_url, temp_config.ca_cert)
+ } else {
+ (None, None)
+ }
}
- /// Helper functions from external_services
fn get_client_builder(
proxy_config: &Proxy,
) -> error_stack::Result<reqwest::ClientBuilder, InjectorError> {
- let mut client_builder = reqwest::Client::builder();
+ let add_proxy = |builder: reqwest::ClientBuilder,
+ proxy: error_stack::Result<reqwest::Proxy, InjectorError>|
+ -> error_stack::Result<reqwest::ClientBuilder, InjectorError> {
+ Ok(builder.proxy(proxy?))
+ };
+
+ let mut builder = reqwest::Client::builder();
- // Configure proxy if provided
- if let Some(proxy_url) = &proxy_config.https_url {
- let proxy = reqwest::Proxy::https(proxy_url)
+ if let Some(url) = &proxy_config.https_url {
+ let proxy = reqwest::Proxy::https(url)
.change_context(InjectorError::HttpRequestFailed)
- .inspect_err(|e| {
- logger::error!("Failed to configure HTTPS proxy: {:?}", e);
- })?;
- client_builder = client_builder.proxy(proxy);
+ .inspect_err(|e| logger::error!("Failed to configure HTTPS proxy: {:?}", e))?;
+ builder = add_proxy(builder, Ok(proxy))?;
}
- if let Some(proxy_url) = &proxy_config.http_url {
- let proxy = reqwest::Proxy::http(proxy_url)
+ if let Some(url) = &proxy_config.http_url {
+ let proxy = reqwest::Proxy::http(url)
.change_context(InjectorError::HttpRequestFailed)
- .inspect_err(|e| {
- logger::error!("Failed to configure HTTP proxy: {:?}", e);
- })?;
- client_builder = client_builder.proxy(proxy);
+ .inspect_err(|e| logger::error!("Failed to configure HTTP proxy: {:?}", e))?;
+ builder = add_proxy(builder, Ok(proxy))?;
}
- Ok(client_builder)
- }
-
- fn get_base_client(
- proxy_config: &Proxy,
- ) -> error_stack::Result<reqwest::Client, InjectorError> {
- let client_builder = get_client_builder(proxy_config)?;
- client_builder
- .build()
- .change_context(InjectorError::HttpRequestFailed)
- .inspect_err(|e| {
- logger::error!("Failed to build default HTTP client: {:?}", e);
- })
+ Ok(builder)
}
fn create_identity_from_certificate_and_key(
@@ -175,7 +206,6 @@ pub mod core {
) -> error_stack::Result<reqwest::Identity, InjectorError> {
let cert_str = encoded_certificate.expose();
let key_str = encoded_certificate_key.expose();
-
let combined_pem = format!("{cert_str}\n{key_str}");
reqwest::Identity::from_pem(combined_pem.as_bytes())
.change_context(InjectorError::HttpRequestFailed)
@@ -191,64 +221,49 @@ pub mod core {
encoded_certificate: hyperswitch_masking::Secret<String>,
) -> error_stack::Result<Vec<reqwest::Certificate>, InjectorError> {
let cert_str = encoded_certificate.expose();
-
let cert = reqwest::Certificate::from_pem(cert_str.as_bytes())
.change_context(InjectorError::HttpRequestFailed)
- .inspect_err(|e| {
- logger::error!("Failed to create certificate from PEM: {:?}", e);
- })?;
+ .inspect_err(|e| logger::error!("Failed to create certificate from PEM: {:?}", e))?;
Ok(vec![cert])
}
- /// Generic function to log HTTP request errors with detailed error type information
fn log_and_convert_http_error(e: reqwest::Error, context: &str) -> InjectorError {
- let error_msg = e.to_string();
- logger::error!("HTTP request failed in {}: {}", context, error_msg);
-
- // Log specific error types for debugging
- if e.is_timeout() {
- logger::error!("Request timed out in {}", context);
- }
- if e.is_connect() {
- logger::error!("Connection error occurred in {}", context);
- }
- if e.is_request() {
- logger::error!("Request construction error in {}", context);
- }
- if e.is_decode() {
- logger::error!("Response decoding error in {}", context);
- }
-
+ logger::error!(
+ context = context,
+ is_timeout = e.is_timeout(),
+ is_connect = e.is_connect(),
+ is_request = e.is_request(),
+ is_decode = e.is_decode(),
+ "HTTP request failed: {}",
+ e
+ );
InjectorError::HttpRequestFailed
}
- /// Apply certificate configuration to request builder and return built request
+ /// Attaches individual certificate values onto a [`RequestBuilder`] and returns the built
+ /// request. Accepts cert fields directly so callers do not need to clone the whole config.
fn build_request_with_certificates(
mut request_builder: RequestBuilder,
- config: &injector_types::ConnectionConfig,
+ client_cert: Option<hyperswitch_masking::Secret<String>>,
+ client_key: Option<hyperswitch_masking::Secret<String>>,
+ ca_cert: Option<hyperswitch_masking::Secret<String>>,
) -> common_utils::request::Request {
- // Add certificate configuration if provided
- if let Some(cert_content) = &config.client_cert {
- request_builder = request_builder.add_certificate(Some(cert_content.clone()));
+ if let Some(cert) = client_cert {
+ request_builder = request_builder.add_certificate(Some(cert));
}
-
- if let Some(key_content) = &config.client_key {
- request_builder = request_builder.add_certificate_key(Some(key_content.clone()));
+ if let Some(key) = client_key {
+ request_builder = request_builder.add_certificate_key(Some(key));
}
-
- if let Some(ca_content) = &config.ca_cert {
- request_builder = request_builder.add_ca_certificate_pem(Some(ca_content.clone()));
+ if let Some(ca) = ca_cert {
+ request_builder = request_builder.add_ca_certificate_pem(Some(ca));
}
-
request_builder.build()
}
- /// Simplified HTTP client for injector using the proven external_services create_client logic
#[instrument(skip_all)]
pub async fn send_request(
client_proxy: &Proxy,
request: common_utils::request::Request,
- _option_timeout_secs: Option<u64>,
) -> error_stack::Result<reqwest::Response, InjectorError> {
logger::info!(
has_client_cert = request.certificate.is_some(),
@@ -317,6 +332,10 @@ pub mod core {
Ok(response)
}
+ // ---------------------------------------------------------------------------
+ // Error type
+ // ---------------------------------------------------------------------------
+
#[derive(Error, Debug)]
pub enum InjectorError {
#[error("Token replacement failed: {0}")]
@@ -329,53 +348,160 @@ pub mod core {
InvalidTemplate(String),
}
- #[instrument(skip_all)]
- pub async fn injector_core(
- request: InjectorRequest,
- ) -> error_stack::Result<InjectorResponse, InjectorError> {
- let start_time = std::time::Instant::now();
- logger::info!("Starting injector_core processing");
+ // ---------------------------------------------------------------------------
+ // VaultConnectorStrategy trait
+ //
+ // Each vault connector variant implements this trait to encapsulate both:
+ // 1. how to process the payload template (interpolate vs. keep placeholders)
+ // 2. how to route the processed payload (direct HTTP vs. vault proxy)
+ //
+ // Adding a new vault connector only requires implementing this trait; the
+ // orchestration in `Injector::run` never needs to change.
+ // ---------------------------------------------------------------------------
- // Extract values for metrics before moving request
- let vault_connector_str = format!("{:?}", request.token_data.vault_connector);
- let http_method_str = format!("{:?}", request.connection_config.http_method);
+ #[async_trait]
+ trait VaultConnectorStrategy: Send + Sync {
+ /// Transform the raw template into a payload ready for the HTTP call.
+ ///
+ /// - **Proxy** (e.g. VGS): interpolate `{{$field}}` with token aliases so the
+ /// forward proxy can detokenize them on the wire.
+ /// - **Transformation** (e.g. HyperswitchVault): return the template unchanged;
+ /// the vault resolves placeholders downstream.
+ fn process_payload(
+ &self,
+ injector: &Injector,
+ template: String,
+ vault_data: &Value,
+ ) -> error_stack::Result<String, InjectorError>;
- // Track total number of invocations with vault connector dimension
- metrics::INJECTOR_INVOCATIONS_COUNT.add(
- 1,
- router_env::metric_attributes!(("vault_connector", vault_connector_str.clone())),
- );
+ /// Send the processed payload and return the connector response.
+ async fn send(
+ &self,
+ injector: &Injector,
+ request: &InjectorRequest,
+ processed_payload: &str,
+ content_type: &ContentType,
+ ) -> error_stack::Result<InjectorResponse, InjectorError>;
+ }
- // Extract endpoint host for dimension (privacy-friendly)
- let endpoint_host = request
- .connection_config
- .endpoint
- .parse::<url::Url>()
- .map(|url| url.host_str().unwrap_or("unknown").to_string())
- .unwrap_or_else(|_| "invalid_url".to_string());
+ // ---- VGS / Proxy strategy --------------------------------------------------
- let injector = Injector::new();
- let result = injector.injector_core(request).await;
+ struct ProxyStrategy;
- // Record total request time and track success/failure
- let request_duration = start_time.elapsed();
+ #[async_trait]
+ impl VaultConnectorStrategy for ProxyStrategy {
+ fn process_payload(
+ &self,
+ injector: &Injector,
+ template: String,
+ vault_data: &Value,
+ ) -> error_stack::Result<String, InjectorError> {
+ logger::debug!("Proxy vault: interpolating template with token aliases");
+ injector.interpolate_string_template_with_vault_data(template, vault_data)
+ }
- let base_attributes = router_env::metric_attributes!(
- ("vault_connector", vault_connector_str.clone()),
- ("http_method", http_method_str.clone()),
- ("endpoint_host", endpoint_host.clone())
- );
+ async fn send(
+ &self,
+ injector: &Injector,
+ request: &InjectorRequest,
+ processed_payload: &str,
+ content_type: &ContentType,
+ ) -> error_stack::Result<InjectorResponse, InjectorError> {
+ injector
+ .make_http_request(&request.connection_config, processed_payload, content_type)
+ .await
+ }
+ }
- metrics::INJECTOR_REQUEST_TIME.record(request_duration.as_secs_f64(), base_attributes);
+ // ---- HyperswitchVault / Transformation strategy ----------------------------
- // Track success/failure metrics
- result.inspect_err(|e| {
- logger::error!("Injector core failed: {:?}", e);
- metrics::INJECTOR_FAILED_TOKEN_REPLACEMENTS_COUNT.add(1, base_attributes);
- })
+ struct HyperswitchVaultStrategy;
+
+ #[async_trait]
+ impl VaultConnectorStrategy for HyperswitchVaultStrategy {
+ fn process_payload(
+ &self,
+ _injector: &Injector,
+ template: String,
+ _vault_data: &Value,
+ ) -> error_stack::Result<String, InjectorError> {
+ logger::debug!(
+ "HyperswitchVault transformation: skipping interpolation, keeping placeholders"
+ );
+ Ok(template)
+ }
+
+ async fn send(
+ &self,
+ injector: &Injector,
+ request: &InjectorRequest,
+ processed_payload: &str,
+ _content_type: &ContentType,
+ ) -> error_stack::Result<InjectorResponse, InjectorError> {
+ logger::debug!("Routing request through HyperswitchVault proxy");
+ injector
+ .make_hyperswitch_vault_request(request, processed_payload)
+ .await
+ }
+ }
+
+ // ---- Fallback strategy for unknown Transformation connectors ---------------
+
+ struct FallbackTransformationStrategy;
+
+ #[async_trait]
+ impl VaultConnectorStrategy for FallbackTransformationStrategy {
+ fn process_payload(
+ &self,
+ _injector: &Injector,
+ template: String,
+ _vault_data: &Value,
+ ) -> error_stack::Result<String, InjectorError> {
+ logger::debug!(
+ "Transformation vault (non-HyperswitchVault): no transformation implemented yet, keeping placeholders"
+ );
+ Ok(template)
+ }
+
+ async fn send(
+ &self,
+ injector: &Injector,
+ request: &InjectorRequest,
+ processed_payload: &str,
+ content_type: &ContentType,
+ ) -> error_stack::Result<InjectorResponse, InjectorError> {
+ logger::debug!(
+ "Transformation vault (non-HyperswitchVault): falling back to direct HTTP request"
+ );
+ injector
+ .make_http_request(&request.connection_config, processed_payload, content_type)
+ .await
+ }
}
- /// Represents a token reference found in a template string
+ impl From<&InjectorRequest> for Box<dyn VaultConnectorStrategy> {
+ fn from(request: &InjectorRequest) -> Self {
+ match (
+ &request.connection_config.vault_connector_type,
+ &request.connection_config.vault_connector_id,
+ ) {
+ (
+ Some(injector_types::VaultConnectorType::Transformation),
+ Some(injector_types::VaultConnectors::HyperswitchVault),
+ ) => Box::new(HyperswitchVaultStrategy),
+ (Some(injector_types::VaultConnectorType::Proxy), _) => Box::new(ProxyStrategy),
+ (Some(injector_types::VaultConnectorType::Transformation), _) => {
+ Box::new(FallbackTransformationStrategy)
+ }
+ _ => Box::new(ProxyStrategy), //by default, the token replacement is done in the forward proxy (e.g. VGS), so ProxyStrategy is the safe default
+ }
+ }
+ }
+
+ // ---------------------------------------------------------------------------
+ // Token parsing helpers
+ // ---------------------------------------------------------------------------
+
#[derive(Debug)]
struct TokenReference {
/// The field name to be replaced (without the {{$}} wrapper)
@@ -421,13 +547,10 @@ pub mod core {
if let Ok((remaining, token_ref)) = parse_token(current_input) {
tokens.push(token_ref);
current_input = remaining;
+ } else if let Some((_, rest)) = current_input.split_at_checked(1) {
+ current_input = rest;
} else {
- // Move forward one character if no token found
- if let Some((_, rest)) = current_input.split_at_checked(1) {
- current_input = rest;
- } else {
- break;
- }
+ break;
}
}
@@ -455,14 +578,58 @@ pub mod core {
})
}
- #[async_trait]
- trait TokenInjector {
- async fn injector_core(
- &self,
- request: InjectorRequest,
- ) -> error_stack::Result<InjectorResponse, InjectorError>;
+ // ---------------------------------------------------------------------------
+ // Public entry point
+ // ---------------------------------------------------------------------------
+
+ #[instrument(skip_all)]
+ pub async fn injector_core(
+ request: InjectorRequest,
+ ) -> error_stack::Result<InjectorResponse, InjectorError> {
+ let start_time = std::time::Instant::now();
+ logger::info!("Starting injector_core processing");
+
+ // Capture metric dimensions before moving `request`
+ let vault_connector_str = request.connection_config.vault_connector_metric_str();
+ let http_method_str = request.connection_config.http_method.as_metric_str();
+ let endpoint_host = request.connection_config.endpoint_host();
+
+ metrics::INJECTOR_INVOCATIONS_COUNT.add(
+ 1,
+ router_env::metric_attributes!(("vault_connector", vault_connector_str)),
+ );
+
+ let injector = Injector::new();
+ let result = injector.injector_core(request).await;
+
+ let request_duration = start_time.elapsed();
+
+ metrics::INJECTOR_REQUEST_TIME.record(
+ request_duration.as_secs_f64(),
+ router_env::metric_attributes!(
+ ("vault_connector", vault_connector_str),
+ ("http_method", http_method_str),
+ ("endpoint_host", endpoint_host.clone())
+ ),
+ );
+
+ result.inspect_err(|e| {
+ logger::error!("Injector core failed: {:?}", e);
+ metrics::INJECTOR_FAILED_TOKEN_REPLACEMENTS_COUNT.add(
+ 1,
+ router_env::metric_attributes!(
+ ("vault_connector", vault_connector_str),
+ ("http_method", http_method_str),
+ ("endpoint_host", endpoint_host)
+ ),
+ );
+ })
}
+ // ---------------------------------------------------------------------------
+ // Injector struct
+ // ---------------------------------------------------------------------------
+
pub struct Injector;
impl Injector {
@@ -470,131 +637,136 @@ pub mod core {
Self
}
- /// Processes a string template and replaces token references with vault data
+ /// Top-level orchestration: select strategy -> process payload -> send -> record metrics.
#[instrument(skip_all)]
- fn interpolate_string_template_with_vault_data(
+ async fn injector_core(
&self,
- template: String,
- vault_data: &Value,
- vault_connector: &injector_types::VaultConnectors,
- ) -> error_stack::Result<String, InjectorError> {
- let token_replacement_start = std::time::Instant::now();
- // Find all tokens using nom parser
- let tokens = find_all_tokens(&template);
- let mut result = template;
-
- for token_ref in tokens.into_iter() {
- let extracted_field_value = self.extract_field_from_vault_data(
- vault_data,
- &token_ref.field,
- vault_connector,
- )?;
- let token_str = match extracted_field_value {
- Value::String(token_value) => token_value,
- _ => serde_json::to_string(&extracted_field_value).unwrap_or_default(),
- };
+ request: InjectorRequest,
+ ) -> error_stack::Result<InjectorResponse, InjectorError> {
+ let start_time = std::time::Instant::now();
- // Replace the token in the result string
- let token_pattern = format!("{{{{${}}}}}", token_ref.field);
- result = result.replace(&token_pattern, &token_str);
- }
+ let vault_data = request.token_data.specific_token_data.clone().expose();
- // Record token replacement time with vault connector dimension
- let token_replacement_duration = token_replacement_start.elapsed();
- let vault_connector_str = format!("{:?}", vault_connector);
- metrics::INJECTOR_TOKEN_REPLACEMENT_TIME.record(
- token_replacement_duration.as_secs_f64(),
- router_env::metric_attributes!(("vault_connector", vault_connector_str)),
+ logger::debug!(
+ template_length = request.connector_payload.template.len(),
+ vault_connector_type = ?request.connection_config.vault_connector_type,
+ "Processing token injection request"
);
- Ok(result)
- }
+ let strategy = Box::<dyn VaultConnectorStrategy>::from(&request);
- #[instrument(skip_all)]
- fn interpolate_token_references_with_vault_data(
- &self,
- value: Value,
- vault_data: &Value,
- vault_connector: &injector_types::VaultConnectors,
- ) -> error_stack::Result<Value, InjectorError> {
- match value {
- Value::Object(obj) => {
- let new_obj = obj
- .into_iter()
- .map(|(key, val)| {
- self.interpolate_token_references_with_vault_data(
- val,
- vault_data,
- vault_connector,
- )
- .map(|processed| (key, processed))
- })
- .collect::<error_stack::Result<serde_json::Map<_, _>, InjectorError>>()?;
- Ok(Value::Object(new_obj))
- }
- Value::String(s) => {
- let processed_string = self.interpolate_string_template_with_vault_data(
- s,
- vault_data,
- vault_connector,
- )?;
- Ok(Value::String(processed_string))
- }
- _ => Ok(value),
- }
- }
+ // Step 1: process the template
+ let processed_payload = strategy.process_payload(
+ self,
+ request.connector_payload.template.clone(),
+ &vault_data,
+ )?;
- #[instrument(skip_all)]
- fn extract_field_from_vault_data(
- &self,
- vault_data: &Value,
- field_name: &str,
- vault_connector: &injector_types::VaultConnectors,
- ) -> error_stack::Result<Value, InjectorError> {
logger::debug!(
- "Extracting field '{}' from vault data using vault type {:?}",
- field_name,
- vault_connector
+ processed_payload_length = processed_payload.len(),
+ "Token replacement completed"
);
- match vault_data {
- Value::Object(obj) => {
- let raw_value = find_field_recursively_in_vault_data(obj, field_name)
- .ok_or_else(|| {
- error_stack::Report::new(InjectorError::TokenReplacementFailed(
- format!("Field '{field_name}' not found"),
- ))
- })?;
-
- // Apply vault-specific token transformation
- self.apply_vault_specific_transformation(raw_value, vault_connector, field_name)
- }
- _ => Err(error_stack::Report::new(
- InjectorError::TokenReplacementFailed(
- "Vault data is not a valid JSON object".to_string(),
+ // Step 2: determine content-type from headers
+ let content_type = request
+ .connection_config
+ .headers
+ .get("Content-Type")
+ .map(|ct| ContentType::from_header_value(&ct.clone().expose()))
+ .unwrap_or(ContentType::ApplicationXWwwFormUrlencoded);
+
+ // Step 3: send via the strategy
+ let response = strategy
+ .send(self, &request, &processed_payload, &content_type)
+ .await?;
+
+ let elapsed = start_time.elapsed();
+ logger::info!(
+ duration_ms = elapsed.as_millis(),
+ status_code = response.status_code,
+ response_size = serde_json::to_string(&response.response)
+ .map(|s| s.len())
+ .unwrap_or(0),
+ headers_count = response.headers.as_ref().map(|h| h.len()).unwrap_or(0),
+ "Token injection completed successfully"
+ );
+
+ metrics::INJECTOR_SUCCESSFUL_TOKEN_REPLACEMENTS_COUNT.add(
+ 1,
+ router_env::metric_attributes!(
+ ("status_code", response.status_code.to_string()),
+ (
+ "vault_connector",
+ request.connection_config.vault_connector_metric_str()
),
- )),
- }
+ (
+ "http_method",
+ request.connection_config.http_method.as_metric_str()
+ ),
+ ("endpoint_host", request.connection_config.endpoint_host())
+ ),
+ );
+
+ Ok(response)
}
+ /// Replaces `{{$field_name}}` placeholders in `template` with values from `vault_data`.
#[instrument(skip_all)]
- fn apply_vault_specific_transformation(
+ pub(crate) fn interpolate_string_template_with_vault_data(
&self,
- extracted_field_value: Value,
- vault_connector: &injector_types::VaultConnectors,
- field_name: &str,
- ) -> error_stack::Result<Value, InjectorError> {
- match vault_connector {
- injector_types::VaultConnectors::VGS => {
- logger::debug!(
- "VGS vault: Using direct token replacement for field '{}'",
- field_name
- );
- Ok(extracted_field_value)
+ template: String,
+ vault_data: &Value,
+ ) -> error_stack::Result<String, InjectorError> {
+ let token_replacement_start = std::time::Instant::now();
+ let tokens = find_all_tokens(&template);
+
+ let result = tokens.into_iter().try_fold(template, |acc, token_ref| {
+ let token_str = match extract_field_from_vault_data(vault_data, &token_ref.field)? {
+ Value::String(s) => s,
+ other => serde_json::to_string(&other).unwrap_or_default(),
+ };
+ let pattern = format!("{{{{${}}}}}", token_ref.field);
+ Ok::<String, error_stack::Report<InjectorError>>(acc.replace(&pattern, &token_str))
+ })?;
+
+ metrics::INJECTOR_TOKEN_REPLACEMENT_TIME.record(
+ token_replacement_start.elapsed().as_secs_f64(),
+ router_env::metric_attributes!(("operation", "interpolation")),
+ );
+
+ Ok(result)
+ }
+
+ /// Builds a [`RequestContent`] from a raw payload string and a content type.
+ fn build_request_content(payload: &str, content_type: ContentType) -> RequestContent {
+ match content_type {
+ ContentType::ApplicationJson => match serde_json::from_str::<Value>(payload) {
+ Ok(json) => RequestContent::Json(Box::new(json)),
+ Err(e) => {
+ logger::debug!(
+ "Failed to parse payload as JSON: {}, falling back to raw bytes",
+ e
+ );
+ RequestContent::RawBytes(payload.as_bytes().to_vec())
+ }
+ },
+ ContentType::ApplicationXWwwFormUrlencoded => {
+ let form_data: HashMap<String, String> =
+ url::form_urlencoded::parse(payload.as_bytes())
+ .into_owned()
+ .collect();
+ RequestContent::FormUrlEncoded(Box::new(form_data))
+ }
+ ContentType::ApplicationXml | ContentType::TextXml | ContentType::TextPlain => {
+ RequestContent::RawBytes(payload.as_bytes().to_vec())
}
}
}
+ /// Sends the processed payload directly to the connector endpoint.
+ ///
+ /// Vault-metadata extraction (proxy URL + CA cert) is scoped here — it is only
+ /// relevant for the proxy path (e.g. VGS).
#[instrument(skip_all)]
async fn make_http_request(
&self,
@@ -610,25 +782,9 @@ pub mod core {
headers_count = config.headers.len(),
"Making HTTP request to connector"
);
- // Validate inputs first
- if config.endpoint.is_empty() {
- logger::error!("Endpoint URL is empty");
- Err(error_stack::Report::new(InjectorError::InvalidTemplate(
- "Endpoint URL cannot be empty".to_string(),
- )))?;
- }
-
- // Parse and validate the complete endpoint URL
- let url = reqwest::Url::parse(&config.endpoint).map_err(|e| {
- logger::error!("Failed to parse endpoint URL: {}", e);
- error_stack::Report::new(InjectorError::InvalidTemplate(format!(
- "Invalid endpoint URL: {e}"
- )))
- })?;
- logger::debug!("Constructed URL: {}", url);
+ logger::debug!("Constructed URL: {}", config.endpoint);
- // Convert headers to common_utils Headers format safely
let headers: Vec<(String, hyperswitch_masking::Maskable<String>)> = config
.headers
.clone()
@@ -641,230 +797,175 @@ pub mod core {
})
.collect();
- // Determine method and request content
let method = Method::from(config.http_method);
- // Determine request content based on content type with error handling
- let request_content = match content_type {
- ContentType::ApplicationJson => {
- // Try to parse as JSON, fallback to raw string
- match serde_json::from_str::<Value>(payload) {
- Ok(json) => Some(RequestContent::Json(Box::new(json))),
- Err(e) => {
- logger::debug!(
- "Failed to parse payload as JSON: {}, falling back to raw bytes",
- e
- );
- Some(RequestContent::RawBytes(payload.as_bytes().to_vec()))
- }
- }
- }
- ContentType::ApplicationXWwwFormUrlencoded => {
- // Parse form data safely
- let form_data: HashMap<String, String> =
- url::form_urlencoded::parse(payload.as_bytes())
- .into_owned()
- .collect();
- Some(RequestContent::FormUrlEncoded(Box::new(form_data)))
- }
- ContentType::ApplicationXml | ContentType::TextXml => {
- Some(RequestContent::RawBytes(payload.as_bytes().to_vec()))
- }
- ContentType::TextPlain => {
- Some(RequestContent::RawBytes(payload.as_bytes().to_vec()))
- }
- };
-
- // Extract vault metadata directly from headers using existing functions
-
- let (vault_proxy_url, vault_ca_cert) = if config
- .headers
- .contains_key(crate::consts::EXTERNAL_VAULT_METADATA_HEADER)
- {
- let mut temp_config = injector_types::ConnectionConfig::new(
- config.endpoint.clone(),
- config.http_method,
- );
-
- // Use existing vault metadata extraction with fallback
- if temp_config.extract_and_apply_vault_metadata_with_fallback(&config.headers) {
- (temp_config.proxy_url, temp_config.ca_cert)
- } else {
- (None, None)
- }
- } else {
- (None, None)
- };
-
- // Build request safely with certificate configuration
- let mut request_builder = RequestBuilder::new()
- .method(method)
- .url(url.as_str())
- .headers(headers);
-
- if let Some(content) = request_content {
- request_builder = request_builder.set_body(content);
- }
+ // Extract vault metadata (proxy URL + CA cert) from headers when present.
+ // This is specific to the proxy path (e.g. VGS).
+ let (vault_proxy_url, vault_ca_cert) = extract_vault_metadata(
+ &config.headers,
+ config.endpoint.clone(),
+ config.http_method,
+ );
- // Create final config with vault CA certificate if available
- let mut final_config = config.clone();
- let has_vault_ca_cert = vault_ca_cert.is_some();
- if has_vault_ca_cert {
- final_config.ca_cert = vault_ca_cert;
- }
+ // Vault-derived CA cert takes priority; fall back to config's own ca_cert
+ let effective_ca_cert = vault_ca_cert.or_else(|| config.ca_cert.clone());
- // Log certificate configuration (but not the actual content)
logger::info!(
- has_client_cert = final_config.client_cert.is_some(),
- has_client_key = final_config.client_key.is_some(),
- has_ca_cert = final_config.ca_cert.is_some(),
- has_vault_ca_cert = has_vault_ca_cert,
- insecure = final_config.insecure.unwrap_or(false),
- cert_format = ?final_config.cert_format,
+ has_client_cert = config.client_cert.is_some(),
+ has_client_key = config.client_key.is_some(),
+ has_ca_cert = effective_ca_cert.is_some(),
+ insecure = config.insecure.unwrap_or(false),
+ cert_format = ?config.cert_format,
"Certificate configuration applied"
);
- // Build request with certificate configuration applied
- let request = build_request_with_certificates(request_builder, &final_config);
+ let request_builder = RequestBuilder::new()
+ .method(method)
+ .url(config.endpoint.as_str())
+ .headers(headers)
+ .set_body(Self::build_request_content(payload, *content_type));
+
+ let request = build_request_with_certificates(
+ request_builder,
+ config.client_cert.clone(),
+ config.client_key.clone(),
+ effective_ca_cert,
+ );
- // Determine which proxy to use: vault metadata > backup > none
+ // Proxy priority: vault metadata -> backup_proxy_url -> none
let final_proxy_url = vault_proxy_url.or_else(|| config.backup_proxy_url.clone());
-
- let proxy = if let Some(proxy_url) = final_proxy_url {
- let proxy_url_str = proxy_url.expose();
-
- // Set proxy URL for both HTTP and HTTPS traffic
- Proxy {
- http_url: Some(proxy_url_str.clone()),
- https_url: Some(proxy_url_str),
- idle_pool_connection_timeout: Some(90),
- bypass_proxy_hosts: None,
- }
- } else {
- Proxy::default()
- };
-
- // Track outgoing HTTP calls with dimensions
- let endpoint_host = config
- .endpoint
- .parse::<url::Url>()
- .map(|url| url.host_str().unwrap_or("unknown").to_string())
- .unwrap_or_else(|_| "invalid_url".to_string());
+ let proxy = Proxy::from_optional_url(final_proxy_url);
metrics::INJECTOR_OUTGOING_CALLS_COUNT.add(
1,
router_env::metric_attributes!(
- ("http_method", format!("{:?}", config.http_method)),
- ("endpoint_host", endpoint_host)
+ ("http_method", config.http_method.as_metric_str()),
+ ("endpoint_host", config.endpoint_host())
),
);
- // Send request using local standalone http client
- let response = send_request(&proxy, request, None).await?;
-
- // Convert reqwest::Response to InjectorResponse using trait
+ let response = send_request(&proxy, request).await?;
response
.into_injector_response()
.await
- .map_err(|e| error_stack::Report::new(e))
+ .map_err(error_stack::Report::new)
}
- }
- impl Default for Injector {
- fn default() -> Self {
- Self::new()
- }
- }
-
- #[async_trait]
- impl TokenInjector for Injector {
+ /// Wraps the template (with `{{$field_name}}` placeholders intact) into the
+ /// HyperswitchVault proxy request format and sends it to the vault endpoint.
#[instrument(skip_all)]
- async fn injector_core(
+ async fn make_hyperswitch_vault_request(
&self,
- request: InjectorRequest,
+ request: &InjectorRequest,
+ processed_payload: &str,
) -> error_stack::Result<InjectorResponse, InjectorError> {
- let start_time = std::time::Instant::now();
-
- // Extract token data from SecretSerdeValue for vault data lookup
- let vault_data = request.token_data.specific_token_data.expose().clone();
-
- logger::debug!(
- template_length = request.connector_payload.template.len(),
- vault_connector = ?request.token_data.vault_connector,
- "Processing token injection request"
- );
-
- // Process template string directly with vault-specific logic
- let processed_payload = self.interpolate_string_template_with_vault_data(
- request.connector_payload.template,
- &vault_data,
- &request.token_data.vault_connector,
- )?;
-
- logger::debug!(
- processed_payload_length = processed_payload.len(),
- "Token replacement completed"
- );
+ let vault_endpoint = request
+ .connection_config
+ .vault_endpoint
+ .as_ref()
+ .ok_or_else(|| {
+ error_stack::Report::new(InjectorError::InvalidTemplate(
+ "vault_endpoint is required for HyperswitchVault proxy request".to_string(),
+ ))
+ })?;
- // Determine content type from headers or default to form-urlencoded
- let content_type = request
+ let vault_auth = request
.connection_config
- .headers
- .get("Content-Type")
- .and_then(|ct| match ct.clone().expose().as_str() {
- "application/json" => Some(ContentType::ApplicationJson),
- "application/x-www-form-urlencoded" => {
- Some(ContentType::ApplicationXWwwFormUrlencoded)
- }
- "application/xml" => Some(ContentType::ApplicationXml),
- "text/xml" => Some(ContentType::TextXml),
- "text/plain" => Some(ContentType::TextPlain),
- _ => None,
- })
- .unwrap_or(ContentType::ApplicationXWwwFormUrlencoded);
+ .vault_auth_data
+ .as_ref()
+ .ok_or_else(|| {
+ error_stack::Report::new(InjectorError::InvalidTemplate(
+ "vault_auth_data is required for HyperswitchVault proxy request"
+ .to_string(),
+ ))
+ })?;
- // Make HTTP request to connector and return enhanced response
- let response = self
- .make_http_request(
+ let vault_proxy_request =
+ injector_types::HyperswitchVaultProxyRequest::try_from_injector_request(
+ processed_payload,
&request.connection_config,
- &processed_payload,
- &content_type,
+ &request.token_data,
)
- .await?;
+ .map_err(error_stack::Report::new)?;
- let elapsed = start_time.elapsed();
logger::info!(
- duration_ms = elapsed.as_millis(),
- status_code = response.status_code,
- response_size = serde_json::to_string(&response.response)
- .map(|s| s.len())
- .unwrap_or(0),
- headers_count = response.headers.as_ref().map(|h| h.len()).unwrap_or(0),
- "Token injection completed successfully"
+ vault_endpoint = %vault_endpoint,
+ destination_url = %vault_proxy_request.destination_url,
+ method = %vault_proxy_request.method,
+ "Sending request to HyperswitchVault proxy"
);
- // Track successful token replacements with comprehensive dimensions
- let endpoint_host = request
- .connection_config
- .endpoint
- .parse::<url::Url>()
- .map(|url| url.host_str().unwrap_or("unknown").to_string())
- .unwrap_or_else(|_| "invalid_url".to_string());
+ let vault_headers: Vec<(String, hyperswitch_masking::Maskable<String>)> = vec![
+ (
+ "Content-Type".to_string(),
+ hyperswitch_masking::Maskable::new_normal("application/json".to_string()),
+ ),
+ (
+ "Accept".to_string(),
+ hyperswitch_masking::Maskable::new_normal("application/json".to_string()),
+ ),
+ (
+ "Authorization".to_string(),
+ hyperswitch_masking::Maskable::Masked(
+ format!("api-key={}", vault_auth.api_key.clone().expose()).into(),
+ ),
+ ),
+ (
+ "x-profile-id".to_string(),
+ hyperswitch_masking::Maskable::Masked(vault_auth.profile_id.clone()),
+ ),
+ ];
- let vault_connector_str = format!("{:?}", request.token_data.vault_connector);
- let http_method_str = format!("{:?}", request.connection_config.http_method);
+ let request_builder = RequestBuilder::new()
+ .method(Method::Post)
+ .url(vault_endpoint.as_str())
+ .headers(vault_headers)
+ .set_body(RequestContent::Json(Box::new(vault_proxy_request)));
- metrics::INJECTOR_SUCCESSFUL_TOKEN_REPLACEMENTS_COUNT.add(
+ let http_request = request_builder.build();
+
+ let vault_endpoint_host = vault_endpoint.host_str().unwrap_or("unknown").to_string();
+ metrics::INJECTOR_OUTGOING_CALLS_COUNT.add(
1,
router_env::metric_attributes!(
- ("status_code", response.status_code.to_string()),
- ("vault_connector", vault_connector_str),
- ("http_method", http_method_str),
- ("endpoint_host", endpoint_host)
+ ("http_method", "POST"),
+ ("endpoint_host", vault_endpoint_host)
),
);
- Ok(response)
+ let response = send_request(&Proxy::default(), http_request).await?;
+ response
+ .into_injector_response()
+ .await
+ .map_err(error_stack::Report::new)
+ }
+ }
+
+ impl Default for Injector {
+ fn default() -> Self {
+ Self::new()
+ }
+ }
+
+ fn extract_field_from_vault_data(
+ vault_data: &Value,
+ field_name: &str,
+ ) -> error_stack::Result<Value, InjectorError> {
+ logger::debug!("Extracting field '{}' from vault data", field_name);
+
+ match vault_data {
+ Value::Object(obj) => {
+ find_field_recursively_in_vault_data(obj, field_name).ok_or_else(|| {
+ error_stack::Report::new(InjectorError::TokenReplacementFailed(format!(
+ "Field '{field_name}' not found"
+ )))
+ })
+ }
+ _ => Err(error_stack::Report::new(
+ InjectorError::TokenReplacementFailed(
+ "Vault data is not a valid JSON object".to_string(),
+ ),
+ )),
}
}
}
@@ -883,7 +984,6 @@ mod tests {
#[tokio::test]
#[ignore = "Integration test that requires network access"]
async fn test_injector_core_integration() {
- // Create test request
let mut headers = HashMap::new();
headers.insert(
"Content-Type".to_string(),
@@ -906,30 +1006,30 @@ mod tests {
template: "card_number={{$card_number}}&cvv={{$cvv}}&expiry={{$exp_month}}/{{$exp_year}}&amount=50&currency=USD&transaction_type=purchase".to_string(),
},
token_data: TokenData {
- vault_connector: VaultConnectors::VGS,
specific_token_data,
},
connection_config: ConnectionConfig {
- endpoint: "https://api.stripe.com/v1/payment_intents".to_string(),
+ endpoint: url::Url::parse("https://api.stripe.com/v1/payment_intents").unwrap(),
http_method: HttpMethod::POST,
headers,
- proxy_url: None, // Remove proxy that was causing issues
+ proxy_url: None,
backup_proxy_url: None,
- // Certificate fields (None for basic test)
client_cert: None,
client_key: None,
- ca_cert: None, // Empty CA cert for testing
+ ca_cert: None,
insecure: None,
cert_password: None,
cert_format: None,
- max_response_size: None, // Use default
+ max_response_size: None,
+ vault_auth_data: None,
+ vault_connector_id: Some(VaultConnectors::VGS),
+ vault_connector_type: Some(VaultConnectorType::Proxy),
+ vault_endpoint: None,
},
};
- // Test the core function - this will make a real HTTP request to httpbin.org
let result = injector_core(request).await;
- // The request should succeed (httpbin.org should be accessible)
if let Err(ref e) = result {
logger::info!("Error: {e:?}");
}
@@ -940,7 +1040,6 @@ mod tests {
let response = result.unwrap();
- // Print the actual response for demonstration
logger::info!("=== HTTP RESPONSE FROM HTTPBIN.ORG ===");
logger::info!(
"{}",
@@ -948,13 +1047,11 @@ mod tests {
);
logger::info!("=======================================");
- // Response should have a proper status code and response data
assert!(
response.status_code >= 200 && response.status_code < 300,
"Response should have successful status code: {}",
response.status_code
);
-
assert!(
response.response.is_object() || response.response.is_string(),
"Response data should be JSON object or string"
@@ -980,22 +1077,19 @@ mod tests {
"exp_year": "25"
}));
- // Test with insecure flag (skip certificate verification)
let request = InjectorRequest {
connector_payload: ConnectorPayload {
template: "card_number={{$card_number}}&cvv={{$cvv}}&expiry={{$exp_month}}/{{$exp_year}}&amount=50&currency=USD&transaction_type=purchase".to_string(),
},
token_data: TokenData {
- vault_connector: VaultConnectors::VGS,
specific_token_data,
},
connection_config: ConnectionConfig {
- endpoint: "https://httpbin.org/post".to_string(),
+ endpoint: url::Url::parse("https://httpbin.org/post").unwrap(),
http_method: HttpMethod::POST,
headers,
- proxy_url: None, // Remove proxy to make test work reliably
+ proxy_url: None,
backup_proxy_url: None,
- // Test without certificates for basic functionality
client_cert: None,
client_key: None,
ca_cert: None,
@@ -1003,12 +1097,15 @@ mod tests {
cert_password: None,
cert_format: None,
max_response_size: None,
+ vault_auth_data: None,
+ vault_connector_id: Some(VaultConnectors::VGS),
+ vault_connector_type: Some(VaultConnectorType::Proxy),
+ vault_endpoint: None,
},
};
let result = injector_core(request).await;
- // Should succeed even with insecure flag
assert!(
result.is_ok(),
"Certificate test should succeed: {result:?}"
@@ -1016,7 +1113,6 @@ mod tests {
let response = result.unwrap();
- // Print the actual response for demonstration
logger::info!("=== CERTIFICATE TEST RESPONSE ===");
logger::info!(
"{}",
@@ -1024,21 +1120,17 @@ mod tests {
);
logger::info!("================================");
- // Should succeed with proper status code
assert!(
response.status_code >= 200 && response.status_code < 300,
"Certificate test should have successful status code: {}",
response.status_code
);
- // Verify the tokens were replaced correctly in the form data
- // httpbin.org returns the request data in the 'form' field
let response_str = serde_json::to_string(&response.response).unwrap_or_default();
- // Check that our test tokens were replaced with the actual values from vault data
- let tokens_replaced = response_str.contains("4242429789164242") && // card_number
- response_str.contains("123") && // cvv
- response_str.contains("12/25"); // expiry
+ let tokens_replaced = response_str.contains("4242429789164242")
+ && response_str.contains("123")
+ && response_str.contains("12/25");
assert!(
tokens_replaced,
diff --git a/crates/injector/src/types.rs b/crates/injector/src/types.rs
index 8e2194b1ee..20f7bd1d41 100644
--- a/crates/injector/src/types.rs
+++ b/crates/injector/src/types.rs
@@ -3,7 +3,7 @@ pub mod models {
use async_trait::async_trait;
use common_utils::pii::SecretSerdeValue;
- use hyperswitch_masking::Secret;
+ use hyperswitch_masking::{ExposeInterface, Secret};
use router_env::logger;
use serde::{Deserialize, Serialize};
@@ -20,6 +20,21 @@ pub mod models {
TextPlain,
}
+ impl ContentType {
+ /// Parse a `Content-Type` header value string into a [`ContentType`].
+ /// Returns the default (`ApplicationXWwwFormUrlencoded`) for unknown values.
+ pub fn from_header_value(value: &str) -> Self {
+ match value {
+ "application/json" => Self::ApplicationJson,
+ "application/x-www-form-urlencoded" => Self::ApplicationXWwwFormUrlencoded,
+ "application/xml" => Self::ApplicationXml,
+ "text/xml" => Self::TextXml,
+ "text/plain" => Self::TextPlain,
+ _ => Self::ApplicationXWwwFormUrlencoded,
+ }
+ }
+ }
+
/// HTTP methods supported by the injector
#[derive(Clone, Copy, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize)]
#[serde(rename_all = "UPPERCASE")]
@@ -31,6 +46,19 @@ pub mod models {
DELETE,
}
+ impl HttpMethod {
+ /// Returns a stable string representation suitable for metric dimensions.
+ pub fn as_metric_str(self) -> &'static str {
+ match self {
+ Self::GET => "GET",
+ Self::POST => "POST",
+ Self::PUT => "PUT",
+ Self::PATCH => "PATCH",
+ Self::DELETE => "DELETE",
+ }
+ }
+ }
+
/// Vault connectors supported by the injector for token management
///
/// Currently supports VGS as the primary vault connector. While only VGS is
@@ -42,15 +70,25 @@ pub mod models {
pub enum VaultConnectors {
/// VGS (Very Good Security) vault connector
VGS,
+ HyperswitchVault,
+ }
+
+ impl VaultConnectors {
+ /// Returns a stable string representation suitable for metric dimensions.
+ pub fn as_metric_str(self) -> &'static str {
+ match self {
+ Self::VGS => "VGS",
+ Self::HyperswitchVault => "HyperswitchVault",
+ }
+ }
}
/// Token data containing vault-specific information for token replacement
#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct TokenData {
- /// The specific token data retrieved from the vault
+ /// The specific token data retrieved from the vault.
+ /// Contains token aliases mapped to field names (never real card data).
pub specific_token_data: SecretSerdeValue,
- /// The type of vault connector being used (e.g., VGS)
- pub vault_connector: VaultConnectors,
}
/// Connector payload containing the template to be processed
@@ -64,11 +102,23 @@ pub mod models {
#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct ConnectionConfig {
/// Complete URL endpoint for the connector (e.g., "https://api.stripe.com/v1/payment_intents")
- pub endpoint: String,
+ pub endpoint: url::Url,
/// HTTP method to use for the request
pub http_method: HttpMethod,
/// HTTP headers to include in the request
pub headers: HashMap<String, Secret<String>>,
+
+ /// Optional vault endpoint to use for token retrieval (overrides default vault endpoint if provided)
+ pub vault_endpoint: Option<url::Url>,
+
+ /// Optional vault connector type to use for token retrieval (overrides default vault connector if provided)
+ pub vault_connector_id: Option<VaultConnectors>,
+
+ /// Optional vault authentication data for authenticating with the vault connector (e.g., API keys, client credentials, etc.)
+ pub vault_auth_data: Option<VaultConnectorAuth>,
+
+ /// Optional vault connector type to use for token retrieval (overrides default vault connector if provided)
+ pub vault_connector_type: Option<VaultConnectorType>,
/// Optional proxy URL for routing the request through a proxy server
pub proxy_url: Option<Secret<String>>,
/// Optional backup proxy URL to use if vault metadata doesn't provide one
@@ -90,6 +140,95 @@ pub mod models {
pub max_response_size: Option<usize>,
}
+ #[derive(Debug, Clone, Deserialize, Serialize)]
+ #[serde(rename_all = "snake_case")]
+ pub enum VaultConnectorType {
+ /// Proxy vault - forwards requests through a proxy (e.g., VGS forward proxy)
+ Proxy,
+ /// Transformation vault - transforms/tokenizes data (e.g., HyperswitchVault)
+ Transformation,
+ }
+
+ #[derive(Debug, Clone, Deserialize, Serialize)]
+ pub struct VaultConnectorAuth {
+ /// API key for authenticating with the vault connector
+ pub api_key: Secret<String>,
+ /// API secret for authenticating with the vault connector
+ pub profile_id: Secret<String>,
+ }
+
+ /// Request body for HyperswitchVault proxy endpoint.
+ ///
+ /// The HS Vault proxy receives the original template (with {{$field_name}} placeholders),
+ /// the destination connector URL, headers, and a token reference. The vault resolves
+ /// placeholders with actual card data and forwards the request to the destination.
+ #[derive(Clone, Debug, Serialize, Deserialize)]
+ 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,
+ /// 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.)
+ pub headers: HashMap<String, Secret<String>>,
+ /// The single token reference extracted from specific_token_data.card_number.
+ /// For HyperswitchVault, all fields share the same token value.
+ pub token: String,
+
+ pub token_type: String,
+ /// HTTP method to use for the forwarded request
+ pub method: String,
+ }
+
+ impl HyperswitchVaultProxyRequest {
+ /// Constructs a HyperswitchVaultProxyRequest from the injector request components.
+ ///
+ /// Extracts the single shared token from `specific_token_data.card_number`
+ /// (HyperswitchVault uses a single token for all fields).
+ pub fn try_from_injector_request(
+ processed_payload: &str,
+ connection_config: &ConnectionConfig,
+ token_data: &TokenData,
+ ) -> Result<Self, crate::injector::core::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
+ .as_object()
+ .and_then(|obj| obj.get("card_number"))
+ .and_then(|v| v.as_str())
+ .map(|s| s.to_string())
+ .ok_or_else(|| {
+ crate::injector::core::InjectorError::InvalidTemplate(
+ "card_number field is required in specific_token_data for HyperswitchVault"
+ .to_string(),
+ )
+ })?;
+
+ // 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()));
+
+ // Convert connector headers from Secret<String> → plain String for the vault request
+ let headers: HashMap<String, Secret<String>> = connection_config
+ .headers
+ .iter()
+ .map(|(k, v)| (k.clone(), v.clone()))
+ .collect();
+
+ let method = connection_config.http_method.as_metric_str().to_string();
+
+ Ok(Self {
+ request_body,
+ destination_url: connection_config.endpoint.clone(),
+ headers,
+ token,
+ token_type: "payment_method_token".to_string(),
+ method,
+ })
+ }
+ }
+
/// Complete request structure for the injector service
#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct InjectorRequest {
@@ -181,7 +320,7 @@ pub mod models {
/// Creates a new InjectorRequest
#[allow(clippy::too_many_arguments)]
pub fn new(
- endpoint: String,
+ endpoint: url::Url,
http_method: HttpMethod,
template: String,
token_data: TokenData,
@@ -213,11 +352,15 @@ pub mod models {
impl ConnectionConfig {
/// Creates a new ConnectionConfig from basic parameters
- pub fn new(endpoint: String, http_method: HttpMethod) -> Self {
+ pub fn new(endpoint: url::Url, http_method: HttpMethod) -> Self {
Self {
endpoint,
http_method,
headers: HashMap::new(),
+ vault_endpoint: None,
+ vault_connector_id: None,
+ vault_auth_data: None,
+ vault_connector_type: None,
proxy_url: None,
backup_proxy_url: None,
client_cert: None,
@@ -229,6 +372,20 @@ pub mod models {
max_response_size: None,
}
}
+
+ /// Extracts the host portion of the endpoint URL for use as a metric dimension.
+ /// Returns `"unknown"` when the host cannot be determined, or `"invalid_url"` when
+ /// the endpoint cannot be parsed as a URL at all.
+ pub fn endpoint_host(&self) -> String {
+ self.endpoint.host_str().unwrap_or("unknown").to_string()
+ }
+
+ /// 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
+ .map(VaultConnectors::as_metric_str)
+ .unwrap_or("None")
+ }
}
}
diff --git a/crates/injector/src/vault_metadata.rs b/crates/injector/src/vault_metadata.rs
index 6404d73c4d..037e1d3cc5 100644
--- a/crates/injector/src/vault_metadata.rs
+++ b/crates/injector/src/vault_metadata.rs
@@ -297,19 +297,20 @@ mod tests {
use std::collections::HashMap;
use base64::Engine;
- use common_utils::pii::SecretSerdeValue;
use super::*;
- use crate::types::{HttpMethod, InjectorRequest, TokenData, VaultConnectors};
+ use crate::types::HttpMethod;
#[test]
fn test_vault_metadata_processing() {
- // Create test VGS metadata with base64 encoded certificate
+ // Create test VGS metadata with a PEM-format certificate
let vgs_metadata = VgsMetadata {
proxy_url: "https://vgs-proxy.example.com:8443"
.parse()
.expect("Valid test URL"),
- certificate: Secret::new("cert".to_string()),
+ certificate: Secret::new(
+ "-----BEGIN CERTIFICATE-----\nMIIBtest\n-----END CERTIFICATE-----".to_string(),
+ ),
};
let metadata = ExternalVaultProxyMetadata::VgsMetadata(vgs_metadata);
@@ -334,31 +335,26 @@ mod tests {
Secret::new(base64_metadata),
);
- // Test the amazing automatic processing with the unified API!
- let injector_request = InjectorRequest::new(
- "https://api.example.com/v1/payments".to_string(),
+ // Test vault metadata extraction directly on ConnectionConfig
+ let mut connection_config = ConnectionConfig::new(
+ Url::parse("https://api.example.com/v1/payments").unwrap(),
HttpMethod::POST,
- "amount={{$amount}}&currency={{$currency}}".to_string(),
- TokenData {
- vault_connector: VaultConnectors::VGS,
- specific_token_data: SecretSerdeValue::new(serde_json::json!({
- "amount": "1000",
- "currency": "USD"
- })),
- },
- Some(headers),
- None, // No fallback proxy needed - vault metadata provides it
- None, // No fallback client cert
- None, // No fallback client key
- None, // No fallback CA cert
+ );
+ connection_config.headers = headers;
+
+ // Extract and apply vault metadata
+ let result =
+ connection_config.extract_and_apply_vault_metadata(&connection_config.headers.clone());
+ assert!(
+ result.is_ok(),
+ "Vault metadata extraction should succeed: {result:?}"
);
- // Verify vault metadata was automatically applied!
- assert!(injector_request.connection_config.proxy_url.is_some());
- assert!(injector_request.connection_config.ca_cert.is_some());
+ // Verify vault metadata was applied to connection config
+ assert!(connection_config.proxy_url.is_some());
+ assert!(connection_config.ca_cert.is_some());
assert_eq!(
- injector_request
- .connection_config
+ connection_config
.proxy_url
.as_ref()
.expect("Proxy URL should be set")
@@ -366,22 +362,6 @@ mod tests {
.expose(),
"https://vgs-proxy.example.com:8443/"
);
-
- // Verify vault metadata header was removed from regular headers
- assert!(!injector_request
- .connection_config
- .headers
- .contains_key(EXTERNAL_VAULT_METADATA_HEADER));
-
- // Verify other headers are preserved
- assert!(injector_request
- .connection_config
- .headers
- .contains_key("Content-Type"));
- assert!(injector_request
- .connection_config
- .headers
- .contains_key("Authorization"));
}
#[test]
diff --git a/crates/router/Cargo.toml b/crates/router/Cargo.toml
index 3ab3bc7df2..92e08f8f3c 100644
--- a/crates/router/Cargo.toml
+++ b/crates/router/Cargo.toml
@@ -90,8 +90,8 @@ reqwest = { version = "0.11.27", features = ["json", "rustls-tls", "gzip", "mult
ring = "0.17.14"
rust_decimal = { version = "1.37.1", features = ["serde-with-float", "serde-with-str"] }
rust-i18n = { git = "https://github.com/kashif-m/rust-i18n", rev = "f2d8096aaaff7a87a847c35a5394c269f75e077a" }
-unified-connector-service-client = { git = "https://github.com/juspay/connector-service", rev = "71fcc81f627c63c4cdc42a8d55eb73f257e3b4c5", package = "rust-grpc-client" }
-unified-connector-service-cards = { git = "https://github.com/juspay/connector-service", rev = "71fcc81f627c63c4cdc42a8d55eb73f257e3b4c5", package = "ucs_cards" }
+unified-connector-service-client = { git = "https://github.com/juspay/connector-service", rev = "2dcbcf76ff0411d8718172ab9e30c5be9688349e", package = "rust-grpc-client" }
+unified-connector-service-cards = { git = "https://github.com/juspay/connector-service", rev = "2dcbcf76ff0411d8718172ab9e30c5be9688349e", package = "ucs_cards" }
rustc-hash = "1.1.0"
rustls = "0.22"
rustls-pemfile = "2"
diff --git a/crates/router/src/core/payments/flows/external_proxy_flow.rs b/crates/router/src/core/payments/flows/external_proxy_flow.rs
index b96c063d9e..d4a3af5fee 100644
--- a/crates/router/src/core/payments/flows/external_proxy_flow.rs
+++ b/crates/router/src/core/payments/flows/external_proxy_flow.rs
@@ -395,7 +395,8 @@ impl Feature<api::ExternalVaultProxy, types::ExternalVaultProxyPaymentsData>
let external_vault_proxy_metadata =
unified_connector_service::build_unified_connector_service_external_vault_proxy_metadata(
- external_vault_merchant_connector_account
+ external_vault_merchant_connector_account,
+ &state.conf.connectors,
)
.change_context(ApiErrorResponse::InternalServerError)
.attach_printable("Failed to construct external vault proxy metadata")?;
diff --git a/crates/router/src/core/unified_connector_service.rs b/crates/router/src/core/unified_connector_service.rs
index 1a871d2860..fdf55d60e3 100644
--- a/crates/router/src/core/unified_connector_service.rs
+++ b/crates/router/src/core/unified_connector_service.rs
@@ -43,7 +43,7 @@ use router_env::{instrument, logger, tracing};
use unified_connector_service_cards::CardNumber;
use unified_connector_service_client::payments::{
self as payments_grpc, payment_method::PaymentMethod, CardDetails, ClassicReward,
- CryptoCurrency, EVoucher, OpenBanking, PaymentServiceAuthorizeResponse,
+ CryptoCurrency, EVoucher, OpenBanking, PaymentServiceAuthorizeResponse, ProxyCardDetails,
};
#[cfg(feature = "v2")]
@@ -1058,7 +1058,11 @@ pub fn build_unified_connector_service_payment_method(
provider
} => {
let eft = payments_grpc::Eft {
- provider,
+ account_number: Some(Secret::new(provider)),
+ branch_code: None,
+ bank_account_holder_name: None,
+ bank_name: Default::default(),
+ bank_type: Default::default(),
};
Ok(payments_grpc::PaymentMethod {
@@ -1668,10 +1672,8 @@ pub fn build_unified_connector_service_payment_method_for_external_proxy(
.card_network
.clone()
.map(payments_grpc::CardNetwork::foreign_from);
- let card_details = CardDetails {
- card_number: Some(CardNumber::from_str(external_vault_card.card_number.peek()).change_context(
- UnifiedConnectorServiceError::RequestEncodingFailedWithReason("Failed to parse card number".to_string())
- )?),
+ let card_details = ProxyCardDetails {
+ card_number: Some(external_vault_card.card_number.expose().into()),
card_exp_month: Some(external_vault_card.card_exp_month.expose().into()),
card_exp_year: Some(external_vault_card.card_exp_year.expose().into()),
card_cvc: Some(external_vault_card.card_cvc.expose().into()),
@@ -1843,12 +1845,8 @@ pub fn parse_merchant_payout_reference_id(id: &str) -> Option<id_type::PayoutRef
#[cfg(feature = "v2")]
pub fn build_unified_connector_service_external_vault_proxy_metadata(
external_vault_merchant_connector_account: MerchantConnectorAccountTypeDetails,
+ connectors: &hyperswitch_domain_models::connector_endpoints::Connectors,
) -> CustomResult<String, UnifiedConnectorServiceError> {
- let external_vault_metadata = external_vault_merchant_connector_account
- .get_metadata()
- .ok_or(UnifiedConnectorServiceError::ParsingFailed)
- .attach_printable("Failed to obtain ConnectorMetadata")?;
-
let connector = external_vault_merchant_connector_account.get_connector_name();
let external_vault_connector =
@@ -1857,37 +1855,86 @@ pub fn build_unified_connector_service_external_vault_proxy_metadata(
.attach_printable(format!("Failed to parse Vault connector: {err}"))
})?;
- let unified_service_vault_metdata = match external_vault_connector {
+ let external_vault_proxy_config = match external_vault_connector {
api_enums::VaultConnectors::Vgs => {
- let vgs_metadata: ExternalVaultConnectorMetadata = external_vault_metadata
- .expose()
- .parse_value("ExternalVaultConnectorMetadata")
+ let external_vault_metadata = external_vault_merchant_connector_account
+ .get_metadata()
+ .ok_or(UnifiedConnectorServiceError::ParsingFailed)
+ .attach_printable("Metadata is required for VGS vault connector")?;
+
+ let external_vault_metadata_parsed: ExternalVaultConnectorMetadata =
+ external_vault_metadata
+ .expose()
+ .parse_value("ExternalVaultConnectorMetadata")
+ .change_context(UnifiedConnectorServiceError::ParsingFailed)
+ .attach_printable("Failed to parse external vault connector metadata")?;
+
+ external_services::grpc_client::unified_connector_service::ExternalVaultProxyConfig {
+ vault_connector_type:
+ external_services::grpc_client::unified_connector_service::VaultConnectorType::Proxy,
+ vault_connector_id: Some("vgs".to_string()),
+ metadata: external_services::grpc_client::unified_connector_service::ExternalVaultProxyMetadata::VgsMetadata(
+ external_services::grpc_client::unified_connector_service::VgsMetadata {
+ proxy_url: external_vault_metadata_parsed.proxy_url,
+ certificate: external_vault_metadata_parsed.certificate,
+ },
+ ),
+ }
+ }
+ api_enums::VaultConnectors::HyperswitchVault => {
+ let base = &connectors.hyperswitch_vault.base_url;
+ let vault_endpoint_url = format!("{}/v2/proxy", base)
+ .parse::<url::Url>()
+ .map(common_utils::types::Url::wrap)
.change_context(UnifiedConnectorServiceError::ParsingFailed)
- .attach_printable("Failed to parse Vgs connector metadata")?;
+ .attach_printable("Failed to parse hyperswitch_vault endpoint URL")?;
- Some(external_services::grpc_client::unified_connector_service::ExternalVaultProxyMetadata::VgsMetadata(
- external_services::grpc_client::unified_connector_service::VgsMetadata {
- proxy_url: vgs_metadata.proxy_url,
- certificate: vgs_metadata.certificate,
+ let auth_type: ConnectorAuthType = external_vault_merchant_connector_account
+ .get_connector_account_details()
+ .change_context(UnifiedConnectorServiceError::FailedToObtainAuthType)
+ .attach_printable("Failed to obtain ConnectorAuthType for HyperswitchVault")?;
+
+ let (api_key, profile_id) = match &auth_type {
+ ConnectorAuthType::SignatureKey {
+ api_key,
+ api_secret,
+ ..
+ } => (api_key.clone(), api_secret.clone()),
+ _ => {
+ return Err(error_stack::report!(
+ UnifiedConnectorServiceError::FailedToObtainAuthType
+ )
+ .attach_printable("HyperswitchVault requires SignatureKey auth type"))
}
- ))
+ };
+
+ external_services::grpc_client::unified_connector_service::ExternalVaultProxyConfig {
+ vault_connector_type:
+ external_services::grpc_client::unified_connector_service::VaultConnectorType::Transformation,
+ vault_connector_id: Some("hyperswitch_vault".to_string()),
+ metadata: external_services::grpc_client::unified_connector_service::ExternalVaultProxyMetadata::HyperswitchVaultMetadata(
+ external_services::grpc_client::unified_connector_service::HyperswitchVaultMetadata {
+ vault_endpoint: vault_endpoint_url,
+ vault_auth_data: external_services::grpc_client::unified_connector_service::VaultConnectorAuth {
+ api_key,
+ profile_id,
+ },
+ },
+ ),
+ }
}
- api_enums::VaultConnectors::HyperswitchVault | api_enums::VaultConnectors::Tokenex => None,
+ api_enums::VaultConnectors::Tokenex => Err(error_stack::report!(
+ UnifiedConnectorServiceError::NotImplemented(
+ "External vault proxy metadata is not supported for Tokenex".to_string(),
+ )
+ ))?,
};
- match unified_service_vault_metdata {
- Some(metdata) => {
- let external_vault_metadata_bytes = serde_json::to_vec(&metdata)
- .change_context(UnifiedConnectorServiceError::ParsingFailed)
- .attach_printable("Failed to convert External vault metadata to bytes")?;
+ let external_vault_config_bytes = serde_json::to_vec(&external_vault_proxy_config)
+ .change_context(UnifiedConnectorServiceError::ParsingFailed)
+ .attach_printable("Failed to serialize ExternalVaultProxyConfig to bytes")?;
- Ok(BASE64_ENGINE.encode(&external_vault_metadata_bytes))
- }
- None => Err(UnifiedConnectorServiceError::NotImplemented(
- "External vault proxy metadata is not supported for {connector_name}".to_string(),
- )
- .into()),
- }
+ Ok(BASE64_ENGINE.encode(&external_vault_config_bytes))
}
pub fn handle_unified_connector_service_response_for_payment_authorize(