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(redis_interface): add TLS connection support for redis cache (#14508)

Pradesh-Seee778723e3f
diff --git a/Cargo.lock b/Cargo.lock
index ff9b77a057..47d32af672 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -3809,9 +3809,13 @@ dependencies = [
"parking_lot 0.12.3",
"rand 0.8.5",
"redis-protocol",
+ "rustls 0.22.4",
+ "rustls-native-certs 0.7.3",
+ "rustls-webpki 0.102.8",
"semver 1.0.26",
"socket2 0.5.10",
"tokio 1.48.0",
+ "tokio-rustls 0.25.0",
"tokio-stream",
"tokio-util",
"tracing",
@@ -8060,10 +8064,13 @@ dependencies = [
"percent-encoding 2.3.1",
"pin-project-lite",
"rand 0.9.2",
+ "rustls 0.23.27",
+ "rustls-native-certs 0.8.1",
"ryu",
"sha1_smol",
"socket2 0.6.1",
"tokio 1.48.0",
+ "tokio-rustls 0.26.2",
"tokio-util",
"url 2.5.4",
"xxhash-rust",
@@ -8095,6 +8102,7 @@ dependencies = [
"hyperswitch_masking",
"redis",
"router_env",
+ "rustls 0.23.27",
"serde",
"serde_json",
"thiserror 1.0.69",
@@ -8783,6 +8791,20 @@ dependencies = [
"sct",
]
+[[package]]
+name = "rustls"
+version = "0.22.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "bf4ef73721ac7bcd79b2b315da7779d8fc09718c6b3d2d1b2d94850eb8c18432"
+dependencies = [
+ "log 0.4.27",
+ "ring 0.17.14",
+ "rustls-pki-types",
+ "rustls-webpki 0.102.8",
+ "subtle",
+ "zeroize",
+]
+
[[package]]
name = "rustls"
version = "0.23.27"
@@ -8811,6 +8833,19 @@ dependencies = [
"security-framework 2.11.1",
]
+[[package]]
+name = "rustls-native-certs"
+version = "0.7.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e5bfb394eeed242e909609f56089eecfe5fda225042e8b171791b9c95f5931e5"
+dependencies = [
+ "openssl-probe",
+ "rustls-pemfile 2.1.3",
+ "rustls-pki-types",
+ "schannel",
+ "security-framework 2.11.1",
+]
+
[[package]]
name = "rustls-native-certs"
version = "0.8.1"
@@ -8861,6 +8896,17 @@ dependencies = [
"untrusted 0.9.0",
]
+[[package]]
+name = "rustls-webpki"
+version = "0.102.8"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "64ca1bc8749bd4cf37b5ce386cc146580777b4e8572c7b97baf22c83f444bee9"
+dependencies = [
+ "ring 0.17.14",
+ "rustls-pki-types",
+ "untrusted 0.9.0",
+]
+
[[package]]
name = "rustls-webpki"
version = "0.103.3"
@@ -10782,6 +10828,17 @@ dependencies = [
"tokio 1.48.0",
]
+[[package]]
+name = "tokio-rustls"
+version = "0.25.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "775e0c0f0adb3a2f22a00c4745d728b479985fc15ee7ca6a2608388c5569860f"
+dependencies = [
+ "rustls 0.22.4",
+ "rustls-pki-types",
+ "tokio 1.48.0",
+]
+
[[package]]
name = "tokio-rustls"
version = "0.26.2"
diff --git a/config/config.example.toml b/config/config.example.toml
index ab0ef615cb..f7a4167846 100644
--- a/config/config.example.toml
+++ b/config/config.example.toml
@@ -107,6 +107,8 @@ host = "127.0.0.1"
port = 6379
# username = "default" # Optional ACL username for authenticated Redis (Redis 6+ / Redis Cloud); requires `password`
# password = "" # Optional password for authenticated Redis (AUTH); leave unset for unauthenticated Redis
+# tls_enabled = true # Connect over TLS (`rediss://`); the server certificate is verified against the platform's trusted CA roots
+# tls_ca_certificate_path = "/path/to/redis_ca.pem" # When set, the server certificate is verified against the CA certificate(s) in this PEM file; when unset, against the platform's trusted CA roots
pool_size = 5 # Number of connections to keep open
reconnect_max_attempts = 5 # Maximum number of reconnection attempts to make before failing. Set to 0 to retry forever.
reconnect_delay = 5 # Delay between reconnection attempts, in milliseconds
diff --git a/config/deployments/drainer.toml b/config/deployments/drainer.toml
index 0fc799ef51..eb711200d2 100644
--- a/config/deployments/drainer.toml
+++ b/config/deployments/drainer.toml
@@ -43,6 +43,8 @@ default_ttl = 300
host = "localhost"
# username = "default" # Optional ACL username for authenticated Redis; requires `password`
# password = "" # Optional password for authenticated Redis (AUTH)
+# tls_enabled = true # Connect over TLS (`rediss://`); the server certificate is verified against the platform's trusted CA roots
+# tls_ca_certificate_path = "/path/to/redis_ca.pem" # When set, the server certificate is verified against the CA certificate(s) in this PEM file; when unset, against the platform's trusted CA roots
pool_size = 5
port = 6379
reconnect_delay = 5
diff --git a/config/deployments/env_specific.toml b/config/deployments/env_specific.toml
index f3bcef3a01..79b993298a 100644
--- a/config/deployments/env_specific.toml
+++ b/config/deployments/env_specific.toml
@@ -235,6 +235,8 @@ host = "127.0.0.1"
port = 6379
# username = "default" # Optional ACL username for authenticated Redis (Redis 6+ / Redis Cloud); requires `password`
# password = "" # Optional password for authenticated Redis (AUTH); leave unset for unauthenticated Redis
+# tls_enabled = true # Connect over TLS (`rediss://`); the server certificate is verified against the platform's trusted CA roots
+# tls_ca_certificate_path = "/path/to/redis_ca.pem" # When set, the server certificate is verified against the CA certificate(s) in this PEM file; when unset, against the platform's trusted CA roots
pool_size = 5 # Number of connections to keep open
reconnect_max_attempts = 5 # Maximum number of reconnection attempts to make before failing. Set to 0 to retry forever.
reconnect_delay = 5 # Delay between reconnection attempts, in milliseconds
diff --git a/config/development.toml b/config/development.toml
index fe4d2ab655..4cb4c1df74 100644
--- a/config/development.toml
+++ b/config/development.toml
@@ -113,6 +113,13 @@ port = 6379
# `default` user); setting `username` requires `password`.
# username = "default"
# password = ""
+# Connect over TLS (`rediss://`); required by most managed Redis offerings
+# (e.g. ElastiCache with encryption in transit, Redis Cloud with TLS).
+# When `tls_ca_certificate_path` is set, the server certificate is verified
+# against the CA certificate(s) in that PEM file (e.g. the Redis Cloud CA
+# bundle); when unset, it is verified against the platform's trusted CA roots.
+# tls_enabled = true
+# tls_ca_certificate_path = "/path/to/redis_ca.pem"
pool_size = 5
reconnect_max_attempts = 5
reconnect_delay = 5
diff --git a/config/docker_compose.toml b/config/docker_compose.toml
index 79e4a7747c..9852c6fa3b 100644
--- a/config/docker_compose.toml
+++ b/config/docker_compose.toml
@@ -158,6 +158,8 @@ host = "redis-standalone"
port = 6379
# username = "default" # Optional ACL username for authenticated Redis; requires `password`
# password = "" # Optional password for authenticated Redis (AUTH)
+# tls_enabled = true # Connect over TLS (`rediss://`); the server certificate is verified against the platform's trusted CA roots
+# tls_ca_certificate_path = "/path/to/redis_ca.pem" # When set, the server certificate is verified against the CA certificate(s) in this PEM file; when unset, against the platform's trusted CA roots
cluster_enabled = false
cluster_urls = ["redis-cluster:6379"]
pool_size = 5
diff --git a/crates/drainer/Cargo.toml b/crates/drainer/Cargo.toml
index 448084af91..f7ec8f000d 100644
--- a/crates/drainer/Cargo.toml
+++ b/crates/drainer/Cargo.toml
@@ -11,7 +11,7 @@ license.workspace = true
default = ["redis-rs"]
release = ["vergen", "external_services/aws_kms", "gcp_kms"]
vergen = ["router_env/vergen"]
-gcp_kms = ["external_services/gcp_kms", "dep:rustls"]
+gcp_kms = ["external_services/gcp_kms"]
v1 = ["diesel_models/v1", "external_services/v1", "hyperswitch_interfaces/v1", "common_utils/v1", "storage_impl/v1", "storage_impl/olap"]
v2 = ["diesel_models/v2", "external_services/v2", "hyperswitch_interfaces/v2", "common_utils/v2", "storage_impl/v2"]
fred = ["redis_interface/fred", "redis_interface/metrics", "storage_impl/fred"]
@@ -32,7 +32,7 @@ rustls = { version = "0.23", default-features = false, features = [
"aws-lc-rs",
"std",
"tls12",
-], optional = true }
+] }
serde = "1.0.219"
serde_json = "1.0.140"
serde_path_to_error = "0.1.17"
diff --git a/crates/drainer/src/main.rs b/crates/drainer/src/main.rs
index 540934c525..abbfd5c35b 100644
--- a/crates/drainer/src/main.rs
+++ b/crates/drainer/src/main.rs
@@ -5,8 +5,7 @@ use router_env::tracing::Instrument;
#[tokio::main]
async fn main() -> DrainerResult<()> {
- // Pin the rustls crypto backend
- #[cfg(feature = "gcp_kms")]
+ // Pin the rustls crypto backend;
#[allow(clippy::expect_used)]
rustls::crypto::aws_lc_rs::default_provider()
.install_default()
diff --git a/crates/redis_interface/Cargo.toml b/crates/redis_interface/Cargo.toml
index c0fcba4d93..b150fad04f 100644
--- a/crates/redis_interface/Cargo.toml
+++ b/crates/redis_interface/Cargo.toml
@@ -27,10 +27,10 @@ tracing = { workspace = true }
# Exactly one backend must be active at compile time
redis = { version = "1.2.0", optional = true, features = [
- "tokio-comp", "cluster-async", "streams", "script", "connection-manager"
+ "tokio-comp", "cluster-async", "streams", "script", "connection-manager", "tokio-rustls-comp"
]}
fred = { version = "8.0.6", optional = true, features = [
- "metrics", "partial-tracing", "subscriber-client"
+ "metrics", "partial-tracing", "subscriber-client", "enable-rustls"
]}
# First party crates
@@ -40,6 +40,7 @@ hyperswitch_masking = "0.0.1"
router_env = { version = "0.1.0", path = "../router_env", optional = true }
[dev-dependencies]
+rustls = { version = "0.23", default-features = false, features = ["aws_lc_rs", "std"] }
tokio = { version = "1.48.0", features = ["macros", "rt-multi-thread"] }
[lints]
diff --git a/crates/redis_interface/src/module/fred.rs b/crates/redis_interface/src/module/fred.rs
index 9ae8bc3ede..5d2d829c4f 100644
--- a/crates/redis_interface/src/module/fred.rs
+++ b/crates/redis_interface/src/module/fred.rs
@@ -242,6 +242,56 @@ impl RedisConnectionPool {
config.username = conf.auth_username().map(ToOwned::to_owned);
config.password = conf.auth_password().map(ToOwned::to_owned);
+ if conf.tls_enabled {
+ let tls_connector = match conf.read_tls_ca_certificates()? {
+ // Verify the server against the CA certificate(s) from the
+ // configured PEM file instead of the platform's trusted roots.
+ Some(ca_pem) => {
+ use fred::rustls::{
+ pki_types::{pem::PemObject, CertificateDer},
+ ClientConfig, RootCertStore,
+ };
+
+ let certificates = CertificateDer::pem_slice_iter(&ca_pem)
+ .collect::<Result<Vec<_>, _>>()
+ .map_err(|error| {
+ error_stack::report!(crate::errors::RedisError::InvalidConfiguration(
+ format!("Failed to parse the Redis CA certificate file: {error}")
+ ))
+ })?;
+
+ if certificates.is_empty() {
+ return Err(error_stack::report!(
+ crate::errors::RedisError::InvalidConfiguration(
+ "The Redis CA certificate file contains no PEM certificates"
+ .to_string()
+ )
+ ));
+ }
+
+ let mut root_store = RootCertStore::empty();
+ for certificate in certificates {
+ root_store.add(certificate).change_context(
+ crate::errors::RedisError::InvalidConfiguration(
+ "Invalid certificate in the Redis CA certificate file".to_string(),
+ ),
+ )?;
+ }
+
+ fred::types::TlsConnector::from(
+ ClientConfig::builder()
+ .with_root_certificates(root_store)
+ .with_no_client_auth(),
+ )
+ }
+ // Verify the server against the platform's trusted CA roots.
+ None => fred::types::TlsConnector::default_rustls()
+ .change_context(crate::errors::RedisError::RedisConnectionError)
+ .attach_printable("Failed to build the TLS configuration for Redis")?,
+ };
+ config.tls = Some(tls_connector.into());
+ }
+
let perf = fred::types::PerformanceConfig {
auto_pipeline: conf.auto_pipeline,
default_command_timeout: std::time::Duration::from_secs(conf.default_command_timeout),
diff --git a/crates/redis_interface/src/module/redis_rs.rs b/crates/redis_interface/src/module/redis_rs.rs
index 9a35a38028..676f92a5e7 100644
--- a/crates/redis_interface/src/module/redis_rs.rs
+++ b/crates/redis_interface/src/module/redis_rs.rs
@@ -190,10 +190,7 @@ impl SubscriberClient {
conf: &crate::types::RedisSettings,
push_sender: tokio::sync::broadcast::Sender<redis::PushInfo>,
) -> CustomResult<SubscriberBackend, crate::errors::RedisError> {
- let connection_info = conf.build_standalone_connection_info()?;
-
- let redis_client = redis::Client::open(connection_info)
- .change_context(crate::errors::RedisError::RedisConnectionError)?;
+ let redis_client = conf.build_standalone_client()?;
let config = conf
.build_connection_manager_config()
@@ -220,7 +217,7 @@ impl SubscriberClient {
let nodes = conf.normalize_cluster_urls();
let mut cluster_builder = conf
- .build_cluster_client_builder(nodes)
+ .build_cluster_client_builder(nodes)?
.push_sender(push_sender);
if conf.max_in_flight_commands > 0 {
@@ -407,7 +404,7 @@ impl RedisConnectionPool {
true => {
let nodes = conf.normalize_cluster_urls();
- let mut pool_builder = conf.build_cluster_client_builder(nodes.clone());
+ let mut pool_builder = conf.build_cluster_client_builder(nodes.clone())?;
if conf.max_in_flight_commands > 0 {
pool_builder =
@@ -435,7 +432,7 @@ impl RedisConnectionPool {
let pool = RedisConn::Cluster(pool_conn);
- let publisher_builder = conf.build_cluster_client_builder(nodes);
+ let publisher_builder = conf.build_cluster_client_builder(nodes)?;
let publisher_conn = publisher_builder
.build()
@@ -463,16 +460,12 @@ impl RedisConnectionPool {
(pool, subscriber, publisher)
}
false => {
- let connection_info = conf.build_standalone_connection_info()?;
-
- let client = redis::Client::open(connection_info)
- .change_context(crate::errors::RedisError::RedisConnectionError)
- .attach_printable_lazy(|| {
- format!(
- "Failed to open Redis client for {}:{}",
- conf.host, conf.port
- )
- })?;
+ let client = conf.build_standalone_client().attach_printable_lazy(|| {
+ format!(
+ "Failed to open Redis client for {}:{}",
+ conf.host, conf.port
+ )
+ })?;
let mut pool_config = conf.build_connection_manager_config();
@@ -489,16 +482,12 @@ impl RedisConnectionPool {
let pool = RedisConn::Standalone(conn);
- let base_connection_info = conf.build_standalone_connection_info()?;
-
- let base_client = redis::Client::open(base_connection_info)
- .change_context(crate::errors::RedisError::RedisConnectionError)
- .attach_printable_lazy(|| {
- format!(
- "Failed to open Redis pub/sub client for {}:{}",
- conf.host, conf.port
- )
- })?;
+ let base_client = conf.build_standalone_client().attach_printable_lazy(|| {
+ format!(
+ "Failed to open Redis pub/sub client for {}:{}",
+ conf.host, conf.port
+ )
+ })?;
let subscriber = Arc::new(SubscriberClient::new(conf).await?);
@@ -622,15 +611,17 @@ impl RedisConnectionPool {
// ─── RedisSettings helpers (redis-rs backend only) ────────────────────────────
impl crate::types::RedisSettings {
- /// Normalize cluster URLs by prepending `"redis://"` if the scheme is missing.
+ /// Normalize cluster URLs by prepending the scheme matching the configured
+ /// transport security (`redis://`, or `rediss://` when TLS is enabled) if
+ /// the scheme is missing.
pub(crate) fn normalize_cluster_urls(&self) -> Vec<String> {
self.cluster_urls
.iter()
.map(|url| {
- if url.starts_with("redis://") {
+ if url.starts_with("redis://") || url.starts_with("rediss://") {
url.clone()
} else {
- format!("redis://{url}")
+ format!("{}://{url}", self.redis_url_scheme())
}
})
.collect()
@@ -651,6 +642,15 @@ impl crate::types::RedisSettings {
})
}
+ /// The URL scheme matching the configured transport security.
+ fn redis_url_scheme(&self) -> &'static str {
+ if self.tls_enabled {
+ "rediss"
+ } else {
+ "redis"
+ }
+ }
+
/// Build standalone connection info with RESP3 protocol from host and port.
pub(crate) fn build_standalone_connection_info(
&self,
@@ -658,7 +658,7 @@ impl crate::types::RedisSettings {
use error_stack::ResultExt;
use redis::IntoConnectionInfo;
- let connection_url = format!("redis://{}:{}", self.host, self.port);
+ let connection_url = format!("{}://{}:{}", self.redis_url_scheme(), self.host, self.port);
let mut connection_info = connection_url
.as_str()
.into_connection_info()
@@ -681,6 +681,31 @@ impl crate::types::RedisSettings {
Ok(connection_info)
}
+ /// Build a standalone [`redis::Client`] from these settings.
+ ///
+ /// When a CA certificate file is configured, the client verifies the
+ /// server certificate against it instead of the platform's trusted roots.
+ pub(crate) fn build_standalone_client(
+ &self,
+ ) -> CustomResult<redis::Client, crate::errors::RedisError> {
+ use error_stack::ResultExt;
+
+ let connection_info = self.build_standalone_connection_info()?;
+
+ match self.read_tls_ca_certificates()? {
+ Some(root_cert) => redis::Client::build_with_tls(
+ connection_info,
+ redis::TlsCertificates {
+ client_tls: None,
+ root_cert: Some(root_cert),
+ },
+ )
+ .change_context(crate::errors::RedisError::RedisConnectionError),
+ None => redis::Client::open(connection_info)
+ .change_context(crate::errors::RedisError::RedisConnectionError),
+ }
+ }
+
/// Build the connection manager configuration from these settings.
///
/// Sets reconnection retries, minimum delay, and optional response timeout.
@@ -706,7 +731,7 @@ impl crate::types::RedisSettings {
pub(crate) fn build_cluster_client_builder(
&self,
nodes: Vec<String>,
- ) -> redis::cluster::ClusterClientBuilder {
+ ) -> CustomResult<redis::cluster::ClusterClientBuilder, crate::errors::RedisError> {
let mut builder = redis::cluster::ClusterClient::builder(nodes)
.retries(self.reconnect_max_attempts)
.min_retry_wait(u64::from(self.reconnect_delay))
@@ -721,8 +746,17 @@ impl crate::types::RedisSettings {
if let Some(password) = self.auth_password() {
builder = builder.password(password);
}
+ if self.tls_enabled {
+ builder = builder.tls(redis::TlsMode::Secure);
+ if let Some(root_cert) = self.read_tls_ca_certificates()? {
+ builder = builder.certs(redis::TlsCertificates {
+ client_tls: None,
+ root_cert: Some(root_cert),
+ });
+ }
+ }
- builder
+ Ok(builder)
}
}
@@ -747,3 +781,77 @@ impl From<&crate::types::RedisSettings> for RedisConfig {
}
}
}
+
+#[cfg(test)]
+mod tests {
+ use crate::types::RedisSettings;
+
+ #[test]
+ fn test_standalone_connection_uses_plain_tcp_by_default() {
+ let settings = RedisSettings::default();
+ let connection_info = settings
+ .build_standalone_connection_info()
+ .expect("failed to build connection info");
+ assert!(matches!(
+ connection_info.addr(),
+ redis::ConnectionAddr::Tcp(..)
+ ));
+ }
+
+ #[test]
+ fn test_standalone_connection_uses_tls_when_enabled() {
+ let settings = RedisSettings {
+ tls_enabled: true,
+ ..RedisSettings::default()
+ };
+ let connection_info = settings
+ .build_standalone_connection_info()
+ .expect("failed to build connection info");
+ assert!(matches!(
+ connection_info.addr(),
+ redis::ConnectionAddr::TcpTls {
+ insecure: false,
+ ..
+ }
+ ));
+ }
+
+ #[test]
+ fn test_normalize_cluster_urls_uses_tls_scheme_when_enabled() {
+ let settings = RedisSettings {
+ tls_enabled: true,
+ cluster_urls: vec![
+ "127.0.0.1:7000".to_string(),
+ "rediss://127.0.0.1:7001".to_string(),
+ ],
+ ..RedisSettings::default()
+ };
+ assert_eq!(
+ settings.normalize_cluster_urls(),
+ vec![
+ "rediss://127.0.0.1:7000".to_string(),
+ "rediss://127.0.0.1:7001".to_string(),
+ ]
+ );
+ }
+
+ #[test]
+ fn test_normalize_cluster_urls_keeps_existing_schemes() {
+ let settings = RedisSettings {
+ cluster_urls: vec![
+ "127.0.0.1:7000".to_string(),
+ "redis://127.0.0.1:7001".to_string(),
+ "rediss://127.0.0.1:7002".to_string(),
+ ],
+ ..RedisSettings::default()
+ };
+ assert_eq!(
+ settings.normalize_cluster_urls(),
+ vec![
+ "redis://127.0.0.1:7000".to_string(),
+ "redis://127.0.0.1:7001".to_string(),
+ "rediss://127.0.0.1:7002".to_string(),
+ ]
+ );
+ }
+}
diff --git a/crates/redis_interface/src/test.rs b/crates/redis_interface/src/test.rs
index 67e08c3eeb..6e918dd228 100644
--- a/crates/redis_interface/src/test.rs
+++ b/crates/redis_interface/src/test.rs
@@ -2519,6 +2519,185 @@ async fn test_authenticated_connection_wrong_password_fails() {
assert!(is_success);
}
+// ─── TLS connections (`rediss://`) ────────────────────────────────────────────
+//
+// These tests run only when a TLS-terminated Redis endpoint is configured via
+// environment variables (they skip otherwise, mirroring the auth tests):
+//
+// TEST_REDIS_TLS_PORT (required to enable)
+// TEST_REDIS_TLS_HOST (optional, default 127.0.0.1)
+// TEST_REDIS_TLS_PASSWORD (optional — for servers that also require AUTH)
+// TEST_REDIS_TLS_USERNAME (optional — ACL user; omit for the default user)
+// TEST_REDIS_TLS_CA_PATH (optional — PEM file with the server's CA, for
+// servers not signed by a platform-trusted CA;
+// maps to the `tls_ca_certificate_path` setting)
+//
+// Local example (self-signed CA):
+// openssl req -x509 -newkey rsa:2048 -nodes -days 2 \
+// -keyout ca.key -out ca.crt -subj "/CN=redis-test-ca"
+// openssl req -newkey rsa:2048 -nodes -keyout redis.key -out redis.csr -subj "/CN=localhost"
+// openssl x509 -req -in redis.csr -CA ca.crt -CAkey ca.key -CAcreateserial -days 2 \
+// -out redis.crt -extfile <(printf "subjectAltName=DNS:localhost,IP:127.0.0.1")
+// docker run -d -p 6390:6390 -v "$PWD":/certs redis:7 redis-server \
+// --port 0 --tls-port 6390 --tls-cert-file /certs/redis.crt \
+// --tls-key-file /certs/redis.key --tls-ca-cert-file /certs/ca.crt \
+// --tls-auth-clients no --requirepass s3cret
+// TEST_REDIS_TLS_CA_PATH="$PWD/ca.crt" TEST_REDIS_TLS_PORT=6390 TEST_REDIS_TLS_PASSWORD=s3cret \
+// cargo test -p redis_interface tls
+//
+// Redis Cloud example (TLS-enabled database):
+// TEST_REDIS_TLS_CA_PATH=<path to the Redis Cloud CA bundle (redis_ca.pem)> \
+// TEST_REDIS_TLS_HOST=redis-12345.c8.us-east-1-2.ec2.redns.redis-cloud.com \
+// TEST_REDIS_TLS_PORT=12345 TEST_REDIS_TLS_PASSWORD=<db password> \
+// cargo test -p redis_interface tls
+
+fn tls_settings_from_env() -> Option<RedisSettings> {
+ let port = std::env::var("TEST_REDIS_TLS_PORT")
+ .ok()?
+ .parse::<u16>()
+ .ok()?;
+
+ let host = std::env::var("TEST_REDIS_TLS_HOST").unwrap_or_else(|_| "127.0.0.1".to_string());
+ let password = std::env::var("TEST_REDIS_TLS_PASSWORD")
+ .ok()
+ .filter(|password| !password.is_empty());
+ let username = std::env::var("TEST_REDIS_TLS_USERNAME")
+ .ok()
+ .filter(|username| !username.is_empty());
+ let tls_ca_certificate_path = std::env::var("TEST_REDIS_TLS_CA_PATH")
+ .ok()
+ .filter(|path| !path.is_empty());
+
+ Some(RedisSettings {
+ host,
+ port,
+ username,
+ password: password.map(Into::into),
+ tls_enabled: true,
+ tls_ca_certificate_path,
+ ..RedisSettings::default()
+ })
+}
+
+async fn get_tls_pool_or_skip() -> Option<RedisConnectionWithContext> {
+ let settings = tls_settings_from_env()?;
+ settings
+ .validate()
+ .expect("TLS redis settings failed validation");
+ Some(
+ test_connection(&settings)
+ .await
+ .expect("failed to connect to redis over TLS"),
+ )
+}
+
+#[tokio::test]
+async fn test_tls_connection_set_get() {
+ let is_success = tokio::task::spawn_blocking(move || {
+ futures::executor::block_on(async {
+ let Some(pool) = get_tls_pool_or_skip().await else {
+ tracing::warn!("SKIP: TLS test skipped — set TEST_REDIS_TLS_PORT to enable");
+ return true;
+ };
+
+ let key: RedisKey = format!("test_tls_set_get_{}", unique_test_id()).into();
+ let value = "tls_value".to_string();
+
+ let set_result = pool.set_key_with_expiry(&key, value.clone(), 60).await;
+ let get_result: Result<String, _> = pool.get_key(&key).await;
+ let del_result = pool.delete_key(&key).await;
+
+ set_result.is_ok()
+ && matches!(get_result, Ok(retrieved) if retrieved == value)
+ && del_result.is_ok()
+ })
+ })
+ .await
+ .expect("Spawn block failure");
+
+ assert!(is_success);
+}
+
+#[tokio::test]
+async fn test_tls_connection_pubsub() {
+ let is_success = tokio::task::spawn_blocking(move || {
+ futures::executor::block_on(async {
+ let Some(pool) = get_tls_pool_or_skip().await else {
+ tracing::warn!("SKIP: TLS test skipped — set TEST_REDIS_TLS_PORT to enable");
+ return true;
+ };
+
+ let channel = format!("test_tls_pubsub_{}", unique_test_id());
+ let test_message = "tls_message";
+
+ pool.redis_conn
+ .subscriber
+ .subscribe(&channel)
+ .await
+ .expect("failed to subscribe on TLS connection");
+
+ let mut receiver = pool.redis_conn.subscriber.message_rx();
+
+ tokio::time::sleep(std::time::Duration::from_millis(100)).await;
+
+ pool.redis_conn
+ .publisher
+ .publish(&channel, RedisValue::from_string(test_message.to_string()))
+ .await
+ .expect("failed to publish on TLS connection");
+
+ let received =
+ tokio::time::timeout(std::time::Duration::from_secs(5), receiver.recv()).await;
+
+ match received {
+ Ok(Ok(msg)) => {
+ let value_str = redis_value_to_option_string(&msg.value);
+ msg.channel == channel && value_str.as_deref() == Some(test_message)
+ }
+ _ => false,
+ }
+ })
+ })
+ .await
+ .expect("Spawn block failure");
+
+ assert!(is_success);
+}
+
+#[tokio::test]
+async fn test_tls_disabled_against_tls_port_fails() {
+ let is_success = tokio::task::spawn_blocking(move || {
+ futures::executor::block_on(async {
+ let Some(mut settings) = tls_settings_from_env() else {
+ tracing::warn!("SKIP: TLS test skipped — set TEST_REDIS_TLS_PORT to enable");
+ return true;
+ };
+
+ // A plaintext handshake against a TLS-only port must be rejected.
+ settings.tls_enabled = false;
+ settings.tls_ca_certificate_path = None;
+
+ match test_connection(&settings).await {
+ Err(_) => true,
+ // Some client stacks consider the pool "connected" once the
+ // TCP connection is accepted, before the server has rejected
+ // the plaintext handshake; in that case an actual command
+ // round trip must still fail.
+ Ok(pool) => {
+ let key: RedisKey = format!("test_tls_disabled_{}", unique_test_id()).into();
+ pool.set_key_with_expiry(&key, "value".to_string(), 60)
+ .await
+ .is_err()
+ }
+ }
+ })
+ })
+ .await
+ .expect("Spawn block failure");
+
+ assert!(is_success);
+}
+
#[tokio::test]
async fn test_cluster_pubsub() {
let (pool, uid) = match get_cluster_pool_with_uid().await {
diff --git a/crates/redis_interface/src/types.rs b/crates/redis_interface/src/types.rs
index bc17b2d485..0a4c7286e7 100644
--- a/crates/redis_interface/src/types.rs
+++ b/crates/redis_interface/src/types.rs
@@ -37,6 +37,29 @@ pub struct RedisSettings {
/// Password for Redis `AUTH` / ACL authentication.
/// When unset, the connection handshake is unauthenticated.
pub password: Option<Secret<String>>,
+ /// When `true`, connect over TLS (the `rediss://` scheme). Required by
+ /// most managed Redis offerings, e.g. AWS ElastiCache with encryption in
+ /// transit, Azure Cache for Redis, or Redis Cloud with TLS enabled.
+ ///
+ /// The server certificate is verified against the platform's trusted CA
+ /// roots unless [`Self::tls_ca_certificate_path`] is set.
+ ///
+ /// With the `redis-rs` backend, the application must make a `rustls`
+ /// crypto provider available — either by having exactly one provider
+ /// feature (`aws_lc_rs` or `ring`) enabled in its dependency graph, or by
+ /// calling `rustls::crypto::CryptoProvider::install_default()` at startup
+ pub tls_enabled: bool,
+ /// Path to a PEM file containing the trusted CA certificate(s) used to
+ /// verify the Redis server certificate, for servers whose certificate is
+ /// issued by a private CA (e.g. the Redis Cloud CA bundle). When set, the
+ /// server certificate is verified against this file instead of the
+ /// platform's trusted CA roots. Only applicable when `tls_enabled` is
+ /// `true`.
+ ///
+ /// Example: `"/etc/hyperswitch/redis_ca.pem"` — an absolute path to a
+ /// file holding one or more `-----BEGIN CERTIFICATE-----` blocks, such
+ /// as the `redis_ca.pem` bundle downloaded from the Redis Cloud console.
+ pub tls_ca_certificate_path: Option<String>,
pub cluster_enabled: bool,
pub cluster_urls: Vec<String>,
pub use_legacy_version: bool,
@@ -84,6 +107,24 @@ impl RedisSettings {
.map(|password| password.peek().as_str())
}
+ /// Read the PEM bytes of the configured CA certificate file, if any.
+ pub(crate) fn read_tls_ca_certificates(
+ &self,
+ ) -> CustomResult<Option<Vec<u8>>, errors::RedisError> {
+ use error_stack::ResultExt;
+
+ self.tls_ca_certificate_path
+ .as_ref()
+ .map(|path| {
+ std::fs::read(path)
+ .change_context(errors::RedisError::InvalidConfiguration(format!(
+ "Failed to read the Redis CA certificate file at `{path}`"
+ )))
+ .attach_printable("`tls_ca_certificate_path` must point to a readable PEM file")
+ })
+ .transpose()
+ }
+
/// Validates the Redis configuration provided.
pub fn validate(&self) -> CustomResult<(), errors::RedisError> {
use common_utils::{ext_traits::ConfigExt, fp_utils::when};
@@ -125,6 +166,31 @@ impl RedisSettings {
},
)?;
+ when(
+ self.tls_ca_certificate_path
+ .as_ref()
+ .is_some_and(|path| path.is_default_or_empty()),
+ || {
+ Err(errors::RedisError::InvalidConfiguration(
+ "Redis `tls_ca_certificate_path` must not be empty when specified".into(),
+ ))
+ },
+ )?;
+
+ when(
+ self.tls_ca_certificate_path.is_some() && !self.tls_enabled,
+ || {
+ Err(errors::RedisError::InvalidConfiguration(
+ "Redis `tls_ca_certificate_path` is only applicable when `tls_enabled` is `true`"
+ .into(),
+ ))
+ },
+ )?;
+
+ // Fail at configuration validation, rather than on the first
+ // connection attempt, when the CA certificate file cannot be read.
+ self.read_tls_ca_certificates()?;
+
when(self.cluster_enabled && self.cluster_urls.is_empty(), || {
Err(errors::RedisError::InvalidConfiguration(
"Redis `cluster_urls` must be specified if `cluster_enabled` is `true`".into(),
@@ -161,6 +227,8 @@ impl Default for RedisSettings {
port: 6379,
username: None,
password: None,
+ tls_enabled: false,
+ tls_ca_certificate_path: None,
cluster_enabled: false,
cluster_urls: vec![],
use_legacy_version: false,
@@ -507,6 +575,7 @@ mod tests {
let settings = RedisSettings::default();
assert_eq!(settings.host, "127.0.0.1");
assert_eq!(settings.port, 6379);
+ assert!(!settings.tls_enabled);
assert!(!settings.cluster_enabled);
assert!(settings.cluster_urls.is_empty());
assert!(!settings.use_legacy_version);
@@ -576,6 +645,81 @@ mod tests {
assert!(settings.validate().is_err());
}
+ /// Create a throwaway CA file on disk so path-based validation can
+ /// exercise the "file is readable" path without external fixtures.
+ fn write_temp_ca_file(name: &str) -> String {
+ let path = std::env::temp_dir().join(format!(
+ "redis_interface_test_{name}_{}.pem",
+ common_utils::process_id()
+ ));
+ std::fs::write(
+ &path,
+ "-----BEGIN CERTIFICATE-----\n-----END CERTIFICATE-----\n",
+ )
+ .expect("failed to write temporary CA file");
+ path.to_string_lossy().into_owned()
+ }
+
+ #[test]
+ fn test_redis_settings_validate_ca_path_with_tls_enabled() {
+ let ca_path = write_temp_ca_file("validate_ok");
+ let settings = RedisSettings {
+ tls_enabled: true,
+ tls_ca_certificate_path: Some(ca_path.clone()),
+ ..RedisSettings::default()
+ };
+ assert!(settings.validate().is_ok());
+ let _ = std::fs::remove_file(ca_path);
+ }
+
+ #[test]
+ fn test_redis_settings_validate_ca_path_without_tls_rejected() {
+ let ca_path = write_temp_ca_file("validate_no_tls");
+ let settings = RedisSettings {
+ tls_enabled: false,
+ tls_ca_certificate_path: Some(ca_path.clone()),
+ ..RedisSettings::default()
+ };
+ assert!(settings.validate().is_err());
+ let _ = std::fs::remove_file(ca_path);
+ }
+
+ #[test]
+ fn test_redis_settings_validate_missing_ca_file_rejected() {
+ let settings = RedisSettings {
+ tls_enabled: true,
+ tls_ca_certificate_path: Some("/nonexistent/path/to/ca.pem".to_string()),
+ ..RedisSettings::default()
+ };
+ assert!(settings.validate().is_err());
+ }
+
+ #[test]
+ fn test_redis_settings_validate_empty_ca_path_rejected() {
+ let settings = RedisSettings {
+ tls_enabled: true,
+ tls_ca_certificate_path: Some(" ".to_string()),
+ ..RedisSettings::default()
+ };
+ assert!(settings.validate().is_err());
+ }
+
+ #[test]
+ fn test_read_tls_ca_certificates_missing_file_fails() {
+ let settings = RedisSettings {
+ tls_enabled: true,
+ tls_ca_certificate_path: Some("/nonexistent/path/to/ca.pem".to_string()),
+ ..RedisSettings::default()
+ };
+ assert!(settings.read_tls_ca_certificates().is_err());
+ }
+
+ #[test]
+ fn test_read_tls_ca_certificates_none_when_unset() {
+ let settings = RedisSettings::default();
+ assert!(matches!(settings.read_tls_ca_certificates(), Ok(None)));
+ }
+
#[test]
fn test_redis_settings_password_masked_in_debug() {
let settings = RedisSettings {
diff --git a/crates/router/src/bin/router.rs b/crates/router/src/bin/router.rs
index 19a5300e40..893d503c31 100644
--- a/crates/router/src/bin/router.rs
+++ b/crates/router/src/bin/router.rs
@@ -8,10 +8,7 @@ use router::{
#[tokio::main]
async fn main() -> ApplicationResult<()> {
- // GCP Cloud KMS pulls in tonic, which requests the `ring` rustls backend — the only
- // thing here that disagrees with the `aws-lc-rs` backend every AWS SDK crate already
- // uses. rustls won't guess between two backends, so pick one explicitly.
- #[cfg(feature = "gcp_kms")]
+ // Pin the process-level rustls crypto backend.
#[allow(clippy::expect_used)]
rustls::crypto::aws_lc_rs::default_provider()
.install_default()
diff --git a/crates/router/src/bin/scheduler.rs b/crates/router/src/bin/scheduler.rs
index 770d6ecbf2..1018a1863c 100644
--- a/crates/router/src/bin/scheduler.rs
+++ b/crates/router/src/bin/scheduler.rs
@@ -29,8 +29,7 @@ use tokio::sync::{mpsc, oneshot};
const SCHEDULER_FLOW: &str = "SCHEDULER_FLOW";
#[tokio::main]
async fn main() -> CustomResult<(), ProcessTrackerError> {
- // Pin the rustls crypto backend
- #[cfg(feature = "gcp_kms")]
+ // Pin the rustls crypto backend;
#[allow(clippy::expect_used)]
rustls::crypto::aws_lc_rs::default_provider()
.install_default()