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

chore(injector): injector change for proxy (#9460)

Shivansh Mathur97d034a2b1c6
diff --git a/crates/injector/src/injector.rs b/crates/injector/src/injector.rs
index 2373940ace..705101bc03 100644
--- a/crates/injector/src/injector.rs
+++ b/crates/injector/src/injector.rs
@@ -16,7 +16,10 @@ pub mod core {
use thiserror::Error;
use crate as injector_types;
- use crate::types::{ContentType, InjectorRequest, InjectorResponse, IntoInjectorResponse};
+ use crate::{
+ types::{ContentType, InjectorRequest, InjectorResponse, IntoInjectorResponse},
+ vault_metadata::VaultMetadataExtractorExt,
+ };
impl From<injector_types::HttpMethod> for Method {
fn from(method: injector_types::HttpMethod) -> Self {
@@ -77,7 +80,6 @@ pub mod core {
logger::warn!("All of client certificate, client key, and CA certificate are provided. CA certificate will be ignored in mutual TLS setup.");
}
- logger::debug!("Creating HTTP client with mutual TLS (client cert + key)");
let client_builder = get_client_builder(proxy_config)?;
let identity = create_identity_from_certificate_and_key(
@@ -106,7 +108,6 @@ pub mod core {
// Case 2: Use provided CA certificate for server authentication only (one-way TLS)
if let Some(ca_pem) = ca_certificate {
- logger::debug!("Creating HTTP client with one-way TLS (CA certificate)");
let pem = ca_pem.expose().replace("\\r\\n", "\n"); // Fix escaped newlines
let cert = reqwest::Certificate::from_pem(pem.as_bytes())
.change_context(InjectorError::HttpRequestFailed)
@@ -124,7 +125,6 @@ pub mod core {
}
// Case 3: Default client (no certs)
- logger::debug!("Creating default HTTP client (no client or CA certificates)");
get_base_client(proxy_config)
}
@@ -136,26 +136,21 @@ pub mod core {
// Configure proxy if provided
if let Some(proxy_url) = &proxy_config.https_url {
- logger::debug!("Configuring HTTPS proxy");
-
let proxy = reqwest::Proxy::https(proxy_url)
.change_context(InjectorError::HttpRequestFailed)
.inspect_err(|e| {
logger::error!("Failed to configure HTTPS proxy: {:?}", e);
})?;
client_builder = client_builder.proxy(proxy);
- logger::debug!("HTTPS proxy configured successfully");
}
if let Some(proxy_url) = &proxy_config.http_url {
- logger::debug!("Configuring HTTP proxy");
let proxy = reqwest::Proxy::http(proxy_url)
.change_context(InjectorError::HttpRequestFailed)
.inspect_err(|e| {
logger::error!("Failed to configure HTTP proxy: {:?}", e);
})?;
client_builder = client_builder.proxy(proxy);
- logger::debug!("HTTP proxy configured successfully");
}
Ok(client_builder)
@@ -180,12 +175,6 @@ pub mod core {
let cert_str = encoded_certificate.expose();
let key_str = encoded_certificate_key.expose();
- logger::debug!(
- cert_length = cert_str.len(),
- key_length = key_str.len(),
- "Creating identity from certificate and key"
- );
-
let combined_pem = format!("{cert_str}\n{key_str}");
reqwest::Identity::from_pem(combined_pem.as_bytes())
.change_context(InjectorError::HttpRequestFailed)
@@ -201,10 +190,6 @@ pub mod core {
encoded_certificate: masking::Secret<String>,
) -> error_stack::Result<Vec<reqwest::Certificate>, InjectorError> {
let cert_str = encoded_certificate.expose();
- logger::debug!(
- cert_length = cert_str.len(),
- "Creating certificate from PEM"
- );
let cert = reqwest::Certificate::from_pem(cert_str.as_bytes())
.change_context(InjectorError::HttpRequestFailed)
@@ -243,17 +228,14 @@ pub mod core {
) -> common_utils::request::Request {
// Add certificate configuration if provided
if let Some(cert_content) = &config.client_cert {
- logger::debug!("Adding client certificate content to request builder");
request_builder = request_builder.add_certificate(Some(cert_content.clone()));
}
if let Some(key_content) = &config.client_key {
- logger::debug!("Adding client private key content to request builder");
request_builder = request_builder.add_certificate_key(Some(key_content.clone()));
}
if let Some(ca_content) = &config.ca_cert {
- logger::debug!("Adding CA certificate content to request builder");
request_builder = request_builder.add_ca_certificate_pem(Some(ca_content.clone()));
}
@@ -268,11 +250,9 @@ pub mod core {
_option_timeout_secs: Option<u64>,
) -> error_stack::Result<reqwest::Response, InjectorError> {
logger::info!(
- proxy_url = ?client_proxy,
has_client_cert = request.certificate.is_some(),
has_client_key = request.certificate_key.is_some(),
has_ca_cert = request.ca_certificate.is_some(),
- request_url = %request.url,
"Making HTTP request using standalone injector HTTP client with configuration"
);
@@ -323,7 +303,6 @@ pub mod core {
}
// Send the request
- logger::debug!("Sending HTTP request to connector");
let response = req_builder
.send()
.await
@@ -644,6 +623,27 @@ pub mod core {
}
};
+ // 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)
@@ -654,62 +654,45 @@ pub mod core {
request_builder = request_builder.set_body(content);
}
+ // 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;
+ }
+
// Log certificate configuration (but not the actual content)
logger::info!(
- has_client_cert = config.client_cert.is_some(),
- has_client_key = config.client_key.is_some(),
- has_ca_cert = config.ca_cert.is_some(),
- insecure = config.insecure.unwrap_or(false),
- cert_format = ?config.cert_format,
+ 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,
"Certificate configuration applied"
);
// Build request with certificate configuration applied
- let request = build_request_with_certificates(request_builder, config);
-
- let proxy = if let Some(proxy_url) = &config.proxy_url {
- let proxy_url_str = proxy_url.clone().expose();
- logger::debug!("Using proxy URL from vault metadata");
-
- // Parse URL to determine scheme
- let parsed_proxy_url = reqwest::Url::parse(&proxy_url_str).map_err(|e| {
- logger::error!("Failed to parse proxy URL: {}", e);
- error_stack::Report::new(InjectorError::InvalidTemplate(format!(
- "Invalid proxy URL: {e}"
- )))
- })?;
+ let request = build_request_with_certificates(request_builder, &final_config);
- logger::debug!(
- proxy_scheme = parsed_proxy_url.scheme(),
- proxy_host = ?parsed_proxy_url.host(),
- proxy_port = ?parsed_proxy_url.port(),
- "Parsed proxy URL information"
- );
+ // Determine which proxy to use: vault metadata > backup > none
+ let final_proxy_url = vault_proxy_url.or_else(|| config.backup_proxy_url.clone());
- if parsed_proxy_url.scheme() == "https" {
- logger::debug!("Using HTTPS proxy configuration");
- Proxy {
- http_url: None,
- https_url: Some(proxy_url_str),
- idle_pool_connection_timeout: Some(90),
- bypass_proxy_hosts: None,
- }
- } else {
- logger::debug!("Using HTTP proxy configuration");
- Proxy {
- http_url: Some(proxy_url_str),
- https_url: None,
- idle_pool_connection_timeout: Some(90),
- bypass_proxy_hosts: None,
- }
+ 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 {
- logger::debug!("No proxy configured, using direct connection to target");
Proxy::default()
};
// Send request using local standalone http client
- logger::debug!("Sending HTTP request to connector");
let response = send_request(&proxy, request, None).await?;
// Convert reqwest::Response to InjectorResponse using trait
@@ -733,8 +716,6 @@ pub mod core {
&self,
request: InjectorRequest,
) -> error_stack::Result<InjectorResponse, InjectorError> {
- logger::info!("Starting token injection process");
-
let start_time = std::time::Instant::now();
// Extract token data from SecretSerdeValue for vault data lookup
@@ -846,6 +827,7 @@ mod tests {
http_method: HttpMethod::POST,
headers,
proxy_url: None, // Remove proxy that was causing issues
+ backup_proxy_url: None,
// Certificate fields (None for basic test)
client_cert: None,
client_key: None,
@@ -925,6 +907,7 @@ mod tests {
http_method: HttpMethod::POST,
headers,
proxy_url: None, // Remove proxy to make test work reliably
+ backup_proxy_url: None,
// Test without certificates for basic functionality
client_cert: None,
client_key: None,
diff --git a/crates/injector/src/types.rs b/crates/injector/src/types.rs
index 14ff3c6776..5e5a05f950 100644
--- a/crates/injector/src/types.rs
+++ b/crates/injector/src/types.rs
@@ -3,15 +3,10 @@ pub mod models {
use async_trait::async_trait;
use common_utils::pii::SecretSerdeValue;
- use masking::{ExposeInterface, Secret};
+ use masking::Secret;
use router_env::logger;
use serde::{Deserialize, Serialize};
- // Import vault metadata processing trait at top level
- use crate::{
- consts::EXTERNAL_VAULT_METADATA_HEADER, vault_metadata::VaultMetadataExtractorExt,
- };
-
// Enums for the injector - making it standalone
/// Content types supported by the injector for HTTP requests
@@ -76,6 +71,9 @@ pub mod models {
pub headers: HashMap<String, Secret<String>>,
/// 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
+ #[serde(default)]
+ pub backup_proxy_url: Option<Secret<String>>,
/// Optional client certificate for mutual TLS authentication
pub client_cert: Option<Secret<String>>,
/// Optional client private key for mutual TLS authentication
@@ -166,19 +164,9 @@ pub mod models {
"Processing connector response"
);
- // Try to parse as JSON, fallback to string value with error logging
let response_data = match serde_json::from_str::<serde_json::Value>(&response_text) {
- Ok(json) => {
- logger::debug!("Successfully parsed response as JSON");
- json
- }
- Err(e) => {
- logger::debug!(
- "Failed to parse response as JSON: {}, returning as string",
- e
- );
- serde_json::Value::String(response_text)
- }
+ Ok(json) => json,
+ Err(_e) => serde_json::Value::String(response_text),
};
Ok(InjectorResponse {
@@ -203,30 +191,13 @@ pub mod models {
client_key: Option<Secret<String>>,
ca_cert: Option<Secret<String>>,
) -> Self {
- let mut headers = headers.unwrap_or_default();
+ let headers = headers.unwrap_or_default();
let mut connection_config = ConnectionConfig::new(endpoint, http_method);
- // Process vault metadata if present
- if let Some(vault_header) = headers.remove(EXTERNAL_VAULT_METADATA_HEADER) {
- let vault_header_value = vault_header.expose();
- logger::info!(
- vault_header_length = vault_header_value.len(),
- "Processing vault metadata header in InjectorRequest::new"
- );
- let vault_applied = connection_config
- .extract_and_apply_vault_metadata_with_fallback_from_header(
- &vault_header_value,
- );
- logger::info!(
- vault_applied = vault_applied,
- proxy_configured = connection_config.proxy_url.is_some(),
- ca_cert_configured = connection_config.ca_cert.is_some(),
- "Vault metadata processing result in InjectorRequest::new"
- );
- }
+ // Keep vault metadata header for processing in make_http_request
- // Set fallback configurations
- connection_config.proxy_url = connection_config.proxy_url.or(proxy_url);
+ // Store backup proxy for make_http_request to use as fallback
+ connection_config.backup_proxy_url = proxy_url;
connection_config.client_cert = connection_config.client_cert.or(client_cert);
connection_config.client_key = connection_config.client_key.or(client_key);
connection_config.ca_cert = connection_config.ca_cert.or(ca_cert);
@@ -248,6 +219,7 @@ pub mod models {
http_method,
headers: HashMap::new(),
proxy_url: None,
+ backup_proxy_url: None,
client_cert: None,
client_key: None,
ca_cert: None,
diff --git a/crates/injector/src/vault_metadata.rs b/crates/injector/src/vault_metadata.rs
index a40d58c846..949cef1c3d 100644
--- a/crates/injector/src/vault_metadata.rs
+++ b/crates/injector/src/vault_metadata.rs
@@ -83,40 +83,17 @@ impl VaultMetadataProcessor for VgsMetadata {
&self,
connection_config: &mut ConnectionConfig,
) -> Result<(), VaultMetadataError> {
- logger::debug!(
- proxy_url = %self.proxy_url,
- proxy_url_scheme = self.proxy_url.scheme(),
- proxy_url_host = ?self.proxy_url.host(),
- proxy_url_port = ?self.proxy_url.port(),
- "Starting VGS metadata processing"
- );
-
// Validate and set proxy URL from VGS metadata
let proxy_url_str = self.proxy_url.as_str().to_string();
connection_config.proxy_url = Some(Secret::new(proxy_url_str.clone()));
- logger::info!(
- original_proxy_url = %self.proxy_url,
- processed_proxy_url = %proxy_url_str,
- proxy_url_length = proxy_url_str.len(),
- "Set proxy URL from VGS metadata"
- );
-
// Validate and decode certificate from VGS metadata
let cert_content = self.certificate.clone().expose();
- logger::debug!(
- cert_length = cert_content.len(),
- cert_starts_with_pem = cert_content.starts_with("-----BEGIN"),
- "Processing certificate from VGS metadata"
- );
-
// Check if certificate is base64 encoded and decode if necessary
let decoded_cert = if cert_content.starts_with("-----BEGIN") {
- logger::debug!("Certificate already in PEM format, using as-is");
cert_content
} else {
- logger::debug!("Certificate appears to be base64 encoded, decoding...");
match BASE64_ENGINE.decode(&cert_content) {
Ok(decoded_bytes) => {
let decoded_string = String::from_utf8(decoded_bytes).map_err(|e| {
@@ -124,16 +101,11 @@ impl VaultMetadataProcessor for VgsMetadata {
"Certificate is not valid UTF-8 after base64 decoding: {e}"
))
})?;
- logger::debug!(
- decoded_cert_length = decoded_string.len(),
- "Successfully decoded base64 certificate"
- );
decoded_string
}
Err(e) => {
logger::error!(
error = %e,
- cert_length = cert_content.len(),
"Failed to decode base64 certificate"
);
return Err(VaultMetadataError::CertificateValidationFailed(format!(
@@ -145,15 +117,6 @@ impl VaultMetadataProcessor for VgsMetadata {
connection_config.ca_cert = Some(Secret::new(decoded_cert.clone()));
- logger::info!(
- proxy_url = %self.proxy_url,
- proxy_url_as_str = self.proxy_url.as_str(),
- proxy_url_set = connection_config.proxy_url.is_some(),
- ca_cert_set = connection_config.ca_cert.is_some(),
- ca_cert_length = decoded_cert.len(),
- "Successfully applied VGS vault metadata to connection config"
- );
-
Ok(())
}
@@ -192,24 +155,13 @@ impl VaultMetadataFactory {
return Err(VaultMetadataError::EmptyOrMalformedHeader);
}
- // Log the attempt (without exposing sensitive data)
- logger::debug!(
- header_length = base64_value.len(),
- "Processing vault metadata from base64 header"
- );
-
// Decode base64 with detailed error context
let decoded_bytes = BASE64_ENGINE.decode(base64_value.trim()).map_err(|e| {
logger::error!(
error = %e,
- header_length = base64_value.len(),
"Failed to decode base64 vault metadata header"
);
- VaultMetadataError::Base64DecodingFailed(format!(
- "Invalid base64 encoding: {}. Header length: {}",
- e,
- base64_value.len()
- ))
+ VaultMetadataError::Base64DecodingFailed(format!("Invalid base64 encoding: {e}"))
})?;
// Validate decoded size
@@ -228,14 +180,9 @@ impl VaultMetadataFactory {
serde_json::from_slice(&decoded_bytes).map_err(|e| {
logger::error!(
error = %e,
- decoded_size = decoded_bytes.len(),
"Failed to parse vault metadata JSON"
);
- VaultMetadataError::JsonParsingFailed(format!(
- "Invalid JSON structure: {}. Size: {} bytes",
- e,
- decoded_bytes.len()
- ))
+ VaultMetadataError::JsonParsingFailed(format!("Invalid JSON structure: {e}"))
})?;
logger::info!(
@@ -262,27 +209,16 @@ impl VaultMetadataExtractor for ConnectionConfig {
headers: &HashMap<String, Secret<String>>,
) -> Result<(), VaultMetadataError> {
if let Some(vault_metadata_header) = headers.get(EXTERNAL_VAULT_METADATA_HEADER) {
- logger::debug!(
- header_length = vault_metadata_header.clone().expose().len(),
- "Found vault metadata header, processing..."
- );
-
let processor =
VaultMetadataFactory::from_base64_header(&vault_metadata_header.clone().expose())
.map_err(|e| {
logger::error!(
error = %e,
- header_length = vault_metadata_header.clone().expose().len(),
"Failed to create vault metadata processor from header"
);
e
})?;
- logger::debug!(
- vault_connector = ?processor.vault_connector(),
- "Created vault metadata processor, applying to connection config..."
- );
-
processor.process_metadata(self).map_err(|e| {
logger::error!(
error = %e,
@@ -299,11 +235,6 @@ impl VaultMetadataExtractor for ConnectionConfig {
client_cert_applied = self.client_cert.is_some(),
"Successfully applied vault metadata to connection configuration"
);
- } else {
- logger::debug!(
- available_headers = ?headers.keys().collect::<Vec<_>>(),
- "No vault metadata header found, skipping vault configuration"
- );
}
Ok(())
}