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 username/password authentication support for redis cache (#14184)

Pradesh-Scd3bb021cda7
diff --git a/Cargo.lock b/Cargo.lock
index d442c8d253..f72f71fcdd 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -8087,6 +8087,7 @@ dependencies = [
"error-stack 0.4.1",
"fred",
"futures 0.3.31",
+ "hyperswitch_masking",
"redis",
"router_env",
"serde",
diff --git a/config/config.example.toml b/config/config.example.toml
index 943ccb9b05..d5aab54fa6 100644
--- a/config/config.example.toml
+++ b/config/config.example.toml
@@ -105,6 +105,8 @@ max_lifetime = 1800 # Maximum lifetime in seconds before a connection is r
[redis]
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
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 ac3b16d1c1..0fc799ef51 100644
--- a/config/deployments/drainer.toml
+++ b/config/deployments/drainer.toml
@@ -41,6 +41,8 @@ cluster_enabled = false
cluster_urls = ["redis.cluster.uri-1:8080", "redis.cluster.uri-2:4115"] # List of redis cluster urls
default_ttl = 300
host = "localhost"
+# username = "default" # Optional ACL username for authenticated Redis; requires `password`
+# password = "" # Optional password for authenticated Redis (AUTH)
pool_size = 5
port = 6379
reconnect_delay = 5
diff --git a/config/deployments/env_specific.toml b/config/deployments/env_specific.toml
index 82c2214b10..6b52abee56 100644
--- a/config/deployments/env_specific.toml
+++ b/config/deployments/env_specific.toml
@@ -233,6 +233,8 @@ bypass_proxy_hosts = "localhost, cluster.local" # A comma-separated list of doma
[redis]
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
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 8fcfaecd4f..5e9f9b4dbb 100644
--- a/config/development.toml
+++ b/config/development.toml
@@ -108,6 +108,11 @@ max_lifetime = 1800
[redis]
host = "127.0.0.1"
port = 6379
+# Credentials for authenticated Redis (e.g. Redis Cloud). Leave commented for
+# an unauthenticated local Redis. `username` is optional (defaults to the
+# `default` user); setting `username` requires `password`.
+# username = "default"
+# password = ""
pool_size = 5
reconnect_max_attempts = 5
reconnect_delay = 5
diff --git a/config/docker_compose.toml b/config/docker_compose.toml
index dc41ff7361..f72e874f69 100644
--- a/config/docker_compose.toml
+++ b/config/docker_compose.toml
@@ -156,6 +156,8 @@ vault_private_key = ""
[redis]
host = "redis-standalone"
port = 6379
+# username = "default" # Optional ACL username for authenticated Redis; requires `password`
+# password = "" # Optional password for authenticated Redis (AUTH)
cluster_enabled = false
cluster_urls = ["redis-cluster:6379"]
pool_size = 5
diff --git a/crates/redis_interface/Cargo.toml b/crates/redis_interface/Cargo.toml
index a47023248b..3b6bbdc7e7 100644
--- a/crates/redis_interface/Cargo.toml
+++ b/crates/redis_interface/Cargo.toml
@@ -36,6 +36,7 @@ fred = { version = "8.0.6", optional = true, features = [
# First party crates
common_utils = { version = "0.1.0", path = "../common_utils", features = ["async_ext"] }
deja = { git = "https://github.com/juspay/deja", rev = "de0a42a42248fc22722bc5a385d9fa6a39449e91", optional = true, default-features = false, features = ["error-stack"] }
+hyperswitch_masking = "0.0.1"
router_env = { version = "0.1.0", path = "../router_env", optional = true }
[dev-dependencies]
diff --git a/crates/redis_interface/src/module/fred.rs b/crates/redis_interface/src/module/fred.rs
index dd2709cee0..9ae8bc3ede 100644
--- a/crates/redis_interface/src/module/fred.rs
+++ b/crates/redis_interface/src/module/fred.rs
@@ -238,6 +238,10 @@ impl RedisConnectionPool {
let mut config = fred::types::RedisConfig::from_url(&redis_connection_url)
.change_context(crate::errors::RedisError::RedisConnectionError)?;
+ // ACL / AUTH credentials apply to standalone and cluster alike.
+ config.username = conf.auth_username().map(ToOwned::to_owned);
+ config.password = conf.auth_password().map(ToOwned::to_owned);
+
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 e3fde9e2aa..9a35a38028 100644
--- a/crates/redis_interface/src/module/redis_rs.rs
+++ b/crates/redis_interface/src/module/redis_rs.rs
@@ -664,10 +664,18 @@ impl crate::types::RedisSettings {
.into_connection_info()
.change_context(crate::errors::RedisError::RedisConnectionError)?;
- let redis_settings = connection_info
+ let mut redis_settings = connection_info
.redis_settings()
.clone()
.set_protocol(redis::ProtocolVersion::RESP3);
+
+ if let Some(username) = self.auth_username() {
+ redis_settings = redis_settings.set_username(username);
+ }
+ if let Some(password) = self.auth_password() {
+ redis_settings = redis_settings.set_password(password);
+ }
+
connection_info = connection_info.set_redis_settings(redis_settings);
Ok(connection_info)
@@ -699,13 +707,22 @@ impl crate::types::RedisSettings {
&self,
nodes: Vec<String>,
) -> redis::cluster::ClusterClientBuilder {
- redis::cluster::ClusterClient::builder(nodes)
+ let mut builder = redis::cluster::ClusterClient::builder(nodes)
.retries(self.reconnect_max_attempts)
.min_retry_wait(u64::from(self.reconnect_delay))
.response_timeout(std::time::Duration::from_secs(
self.default_command_timeout.max(1),
))
- .use_protocol(redis::ProtocolVersion::RESP3)
+ .use_protocol(redis::ProtocolVersion::RESP3);
+
+ if let Some(username) = self.auth_username() {
+ builder = builder.username(username);
+ }
+ if let Some(password) = self.auth_password() {
+ builder = builder.password(password);
+ }
+
+ builder
}
}
diff --git a/crates/redis_interface/src/test.rs b/crates/redis_interface/src/test.rs
index 417e881351..2c8621f684 100644
--- a/crates/redis_interface/src/test.rs
+++ b/crates/redis_interface/src/test.rs
@@ -2277,6 +2277,155 @@ async fn test_cluster_scan() {
assert!(is_success);
}
+// ─── Authenticated connections (Redis ACL / AUTH) ─────────────────────────────
+//
+// These tests run only when an authenticated Redis endpoint is configured via
+// environment variables (they skip otherwise, mirroring the cluster tests):
+//
+// TEST_REDIS_AUTH_PASSWORD (required to enable)
+// TEST_REDIS_AUTH_USERNAME (optional — ACL user; omit for the default user)
+// TEST_REDIS_AUTH_HOST (optional, default 127.0.0.1)
+// TEST_REDIS_AUTH_PORT (optional, default 6379)
+//
+// Local example:
+// docker run -d -p 6380:6379 redis:7 redis-server --requirepass s3cret
+// TEST_REDIS_AUTH_PASSWORD=s3cret TEST_REDIS_AUTH_PORT=6380 \
+// cargo test -p redis_interface auth
+//
+// Redis Cloud example:
+// TEST_REDIS_AUTH_HOST=redis-12345.c8.us-east-1-2.ec2.redns.redis-cloud.com \
+// TEST_REDIS_AUTH_PORT=12345 TEST_REDIS_AUTH_PASSWORD=<db password> \
+// cargo test -p redis_interface auth
+
+fn auth_settings_from_env() -> Option<RedisSettings> {
+ let password = std::env::var("TEST_REDIS_AUTH_PASSWORD").ok()?;
+ if password.is_empty() {
+ return None;
+ }
+
+ let host = std::env::var("TEST_REDIS_AUTH_HOST").unwrap_or_else(|_| "127.0.0.1".to_string());
+ let port = std::env::var("TEST_REDIS_AUTH_PORT")
+ .ok()
+ .and_then(|port| port.parse::<u16>().ok())
+ .unwrap_or(6379);
+ let username = std::env::var("TEST_REDIS_AUTH_USERNAME")
+ .ok()
+ .filter(|username| !username.is_empty());
+
+ Some(RedisSettings {
+ host,
+ port,
+ username,
+ password: Some(password.into()),
+ ..RedisSettings::default()
+ })
+}
+
+async fn get_auth_pool_or_skip() -> Option<RedisConnectionWithContext> {
+ let settings = auth_settings_from_env()?;
+ settings
+ .validate()
+ .expect("authenticated redis settings failed validation");
+ Some(
+ test_connection(&settings)
+ .await
+ .expect("failed to connect to authenticated redis"),
+ )
+}
+
+#[tokio::test]
+async fn test_authenticated_connection_set_get() {
+ let is_success = tokio::task::spawn_blocking(move || {
+ futures::executor::block_on(async {
+ let Some(pool) = get_auth_pool_or_skip().await else {
+ tracing::warn!("SKIP: auth test skipped — set TEST_REDIS_AUTH_PASSWORD to enable");
+ return true;
+ };
+
+ let key: RedisKey = format!("test_auth_set_get_{}", unique_test_id()).into();
+ let value = "authenticated_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_authenticated_connection_pubsub() {
+ let is_success = tokio::task::spawn_blocking(move || {
+ futures::executor::block_on(async {
+ let Some(pool) = get_auth_pool_or_skip().await else {
+ tracing::warn!("SKIP: auth test skipped — set TEST_REDIS_AUTH_PASSWORD to enable");
+ return true;
+ };
+
+ let channel = format!("test_auth_pubsub_{}", unique_test_id());
+ let test_message = "authenticated_message";
+
+ pool.redis_conn
+ .subscriber
+ .subscribe(&channel)
+ .await
+ .expect("failed to subscribe on authenticated 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 authenticated 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_authenticated_connection_wrong_password_fails() {
+ let is_success = tokio::task::spawn_blocking(move || {
+ futures::executor::block_on(async {
+ let Some(mut settings) = auth_settings_from_env() else {
+ tracing::warn!("SKIP: auth test skipped — set TEST_REDIS_AUTH_PASSWORD to enable");
+ return true;
+ };
+
+ settings.password = Some("definitely_the_wrong_password".to_string().into());
+
+ test_connection(&settings).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 4312681cce..bc17b2d485 100644
--- a/crates/redis_interface/src/types.rs
+++ b/crates/redis_interface/src/types.rs
@@ -8,6 +8,7 @@
//! because Rust does not allow splitting a struct definition across files.
use common_utils::errors::CustomResult;
+use hyperswitch_masking::{PeekInterface, Secret};
use crate::errors;
@@ -30,6 +31,12 @@ pub struct RedisValue {
pub struct RedisSettings {
pub host: String,
pub port: u16,
+ /// Username for Redis ACL authentication (Redis 6+ / Redis Cloud).
+ /// When unset, the `default` user is assumed.
+ pub username: Option<String>,
+ /// Password for Redis `AUTH` / ACL authentication.
+ /// When unset, the connection handshake is unauthenticated.
+ pub password: Option<Secret<String>>,
pub cluster_enabled: bool,
pub cluster_urls: Vec<String>,
pub use_legacy_version: bool,
@@ -61,6 +68,22 @@ pub struct RedisSettings {
}
impl RedisSettings {
+ /// The configured ACL username, if any.
+ ///
+ /// Emptiness is enforced by [`Self::validate`], not here.
+ pub(crate) fn auth_username(&self) -> Option<&str> {
+ self.username.as_deref()
+ }
+
+ /// The configured password, if any.
+ ///
+ /// Emptiness is enforced by [`Self::validate`], not here.
+ pub(crate) fn auth_password(&self) -> Option<&str> {
+ self.password
+ .as_ref()
+ .map(|password| password.peek().as_str())
+ }
+
/// Validates the Redis configuration provided.
pub fn validate(&self) -> CustomResult<(), errors::RedisError> {
use common_utils::{ext_traits::ConfigExt, fp_utils::when};
@@ -71,6 +94,37 @@ impl RedisSettings {
))
})?;
+ when(
+ self.username
+ .as_ref()
+ .is_some_and(|username| username.is_default_or_empty()),
+ || {
+ Err(errors::RedisError::InvalidConfiguration(
+ "Redis `username` must not be empty when specified".into(),
+ ))
+ },
+ )?;
+
+ when(
+ self.password
+ .as_ref()
+ .is_some_and(|password| password.is_default_or_empty()),
+ || {
+ Err(errors::RedisError::InvalidConfiguration(
+ "Redis `password` must not be empty when specified".into(),
+ ))
+ },
+ )?;
+
+ when(
+ self.auth_username().is_some() && self.auth_password().is_none(),
+ || {
+ Err(errors::RedisError::InvalidConfiguration(
+ "Redis `password` must be specified when `username` is set".into(),
+ ))
+ },
+ )?;
+
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(),
@@ -105,6 +159,8 @@ impl Default for RedisSettings {
Self {
host: "127.0.0.1".to_string(),
port: 6379,
+ username: None,
+ password: None,
cluster_enabled: false,
cluster_urls: vec![],
use_legacy_version: false,
@@ -462,6 +518,74 @@ mod tests {
assert_eq!(settings.max_failure_threshold_seconds, 5);
}
+ #[test]
+ fn test_redis_settings_validate_username_without_password() {
+ let settings = RedisSettings {
+ username: Some("app_user".to_string()),
+ password: None,
+ ..RedisSettings::default()
+ };
+ assert!(settings.validate().is_err());
+ }
+
+ #[test]
+ fn test_redis_settings_validate_username_with_password() {
+ let settings = RedisSettings {
+ username: Some("app_user".to_string()),
+ password: Some("secret".to_string().into()),
+ ..RedisSettings::default()
+ };
+ assert!(settings.validate().is_ok());
+ }
+
+ #[test]
+ fn test_redis_settings_validate_password_only() {
+ let settings = RedisSettings {
+ password: Some("secret".to_string().into()),
+ ..RedisSettings::default()
+ };
+ assert!(settings.validate().is_ok());
+ }
+
+ #[test]
+ fn test_redis_settings_validate_empty_username_rejected() {
+ let settings = RedisSettings {
+ username: Some(String::new()),
+ password: Some("secret".to_string().into()),
+ ..RedisSettings::default()
+ };
+ assert!(settings.validate().is_err());
+ }
+
+ #[test]
+ fn test_redis_settings_validate_whitespace_username_rejected() {
+ let settings = RedisSettings {
+ username: Some(" ".to_string()),
+ password: Some("secret".to_string().into()),
+ ..RedisSettings::default()
+ };
+ assert!(settings.validate().is_err());
+ }
+
+ #[test]
+ fn test_redis_settings_validate_empty_password_rejected() {
+ let settings = RedisSettings {
+ password: Some(String::new().into()),
+ ..RedisSettings::default()
+ };
+ assert!(settings.validate().is_err());
+ }
+
+ #[test]
+ fn test_redis_settings_password_masked_in_debug() {
+ let settings = RedisSettings {
+ password: Some("super_secret".to_string().into()),
+ ..RedisSettings::default()
+ };
+ let debug_output = format!("{settings:?}");
+ assert!(!debug_output.contains("super_secret"));
+ }
+
#[test]
fn test_del_reply_is_key_deleted() {
assert!(DelReply::KeyDeleted.is_key_deleted());