use std::fmt;
use std::future::Future;
use std::pin::Pin;
use std::sync::Arc;
use futures::{Stream, StreamExt};
use redis_tower_commands::Auth;
use redis_tower_core::{Command, ConnectionConfig, ProtocolVersion, RedisConnection, RedisError};
use tokio_util::sync::CancellationToken;
pub type CredentialUpdateStream =
Pin<Box<dyn Stream<Item = Result<Credentials, RedisError>> + Send + 'static>>;
#[derive(Clone, zeroize::Zeroize, zeroize::ZeroizeOnDrop)]
pub struct Credentials {
pub username: Option<String>,
pub password: String,
}
impl fmt::Debug for Credentials {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter
.debug_struct("Credentials")
.field("username", &self.username.as_deref())
.field("password", &"<redacted>")
.finish()
}
}
impl Credentials {
pub fn new(username: impl Into<String>, password: impl Into<String>) -> Self {
Self {
username: Some(username.into()),
password: password.into(),
}
}
pub fn password(password: impl Into<String>) -> Self {
Self {
username: None,
password: password.into(),
}
}
pub fn username(&self) -> Option<&str> {
self.username.as_deref()
}
pub fn password_value(&self) -> &str {
&self.password
}
pub fn auth_command(&self) -> Auth {
match &self.username {
Some(user) => Auth::credentials(user, &self.password),
None => Auth::password(&self.password),
}
}
}
pub trait CredentialProvider: Send + Sync + 'static {
fn get_credentials(
&self,
) -> Pin<Box<dyn Future<Output = Result<Credentials, RedisError>> + Send>>;
fn force_refresh(
&self,
) -> Pin<Box<dyn Future<Output = Result<Credentials, RedisError>> + Send>> {
self.get_credentials()
}
}
pub trait StreamingCredentialProvider: CredentialProvider {
fn subscribe(self: Arc<Self>) -> CredentialUpdateStream;
}
#[must_use = "dropping the handle stops push-based credential reauthentication"]
pub struct CredentialReauthenticationHandle {
cancellation: CancellationToken,
task: Option<tokio::task::JoinHandle<()>>,
}
impl CredentialReauthenticationHandle {
fn new(cancellation: CancellationToken, task: tokio::task::JoinHandle<()>) -> Self {
Self {
cancellation,
task: Some(task),
}
}
pub async fn shutdown(mut self) {
self.cancellation.cancel();
if let Some(task) = self.task.take() {
let _ = task.await;
}
}
}
impl Drop for CredentialReauthenticationHandle {
fn drop(&mut self) {
self.cancellation.cancel();
if let Some(task) = self.task.take() {
task.abort();
}
}
}
pub fn spawn_credential_reauthentication<F, Fut>(
provider: Arc<dyn StreamingCredentialProvider>,
reauthenticate: F,
) -> CredentialReauthenticationHandle
where
F: Fn(Credentials) -> Fut + Send + Sync + 'static,
Fut: Future<Output = Result<(), RedisError>> + Send + 'static,
{
let mut updates = Arc::clone(&provider).subscribe();
let cancellation = CancellationToken::new();
let task_cancellation = cancellation.clone();
let task = tokio::spawn(async move {
loop {
let update = tokio::select! {
() = task_cancellation.cancelled() => break,
update = updates.next() => update,
};
let Some(update) = update else {
break;
};
match update {
Ok(credentials) => {
if let Err(error) = reauthenticate(credentials).await {
tracing::warn!(error = %error, "credential reauthentication failed");
}
}
Err(error) => {
tracing::warn!(error = %error, "credential refresh stream failed");
}
}
}
});
CredentialReauthenticationHandle::new(cancellation, task)
}
#[derive(Debug, Clone)]
pub struct StaticCredentials {
creds: Credentials,
}
impl StaticCredentials {
pub fn new(username: impl Into<String>, password: impl Into<String>) -> Self {
Self {
creds: Credentials::new(username, password),
}
}
pub fn password(password: impl Into<String>) -> Self {
Self {
creds: Credentials::password(password),
}
}
}
impl CredentialProvider for StaticCredentials {
fn get_credentials(
&self,
) -> Pin<Box<dyn Future<Output = Result<Credentials, RedisError>> + Send>> {
let creds = self.creds.clone();
Box::pin(async move { Ok(creds) })
}
}
impl<F, Fut> CredentialProvider for F
where
F: Fn() -> Fut + Send + Sync + 'static,
Fut: Future<Output = Result<Credentials, RedisError>> + Send + 'static,
{
fn get_credentials(
&self,
) -> Pin<Box<dyn Future<Output = Result<Credentials, RedisError>> + Send>> {
Box::pin((self)())
}
}
#[must_use = "a credential connection factory must be passed to a client or pool"]
pub struct CredentialConnectionFactory {
addr: String,
provider: Arc<dyn CredentialProvider>,
connection_config: ConnectionConfig,
#[cfg(any(feature = "tls-rustls", feature = "tls-native-tls"))]
tls: Option<(String, Arc<redis_tower_core::tls::TlsConfig>)>,
}
impl Clone for CredentialConnectionFactory {
fn clone(&self) -> Self {
Self {
addr: self.addr.clone(),
provider: Arc::clone(&self.provider),
connection_config: self.connection_config.clone(),
#[cfg(any(feature = "tls-rustls", feature = "tls-native-tls"))]
tls: self.tls.clone(),
}
}
}
impl CredentialConnectionFactory {
pub fn new(addr: impl Into<String>, provider: impl CredentialProvider) -> Self {
Self::from_shared_provider(addr, Arc::new(provider))
}
pub fn from_shared_provider(
addr: impl Into<String>,
provider: Arc<dyn CredentialProvider>,
) -> Self {
Self {
addr: addr.into(),
provider,
connection_config: ConnectionConfig::default(),
#[cfg(any(feature = "tls-rustls", feature = "tls-native-tls"))]
tls: None,
}
}
pub fn with_connection_config(mut self, config: ConnectionConfig) -> Self {
self.connection_config = config;
self
}
#[cfg(any(feature = "tls-rustls", feature = "tls-native-tls"))]
pub fn with_tls(
mut self,
hostname: impl Into<String>,
tls: redis_tower_core::tls::TlsConfig,
) -> Self {
self.tls = Some((hostname.into(), Arc::new(tls)));
self
}
pub fn provider(&self) -> &dyn CredentialProvider {
self.provider.as_ref()
}
async fn connect_inner(&self) -> Result<RedisConnection, RedisError> {
let requested_protocol = self.connection_config.protocol();
let bootstrap_config = self
.connection_config
.clone()
.with_protocol(ProtocolVersion::Resp2);
#[cfg(any(feature = "tls-rustls", feature = "tls-native-tls"))]
let mut conn = match &self.tls {
Some((hostname, tls)) => {
RedisConnection::connect_tls_with_config(
&self.addr,
hostname,
tls.as_ref(),
&bootstrap_config,
)
.await?
}
None => RedisConnection::connect_with_config(&self.addr, &bootstrap_config).await?,
};
#[cfg(not(any(feature = "tls-rustls", feature = "tls-native-tls")))]
let mut conn = RedisConnection::connect_with_config(&self.addr, &bootstrap_config).await?;
authenticate_with_refresh(&mut conn, self.provider.as_ref()).await?;
conn.negotiate_protocol(requested_protocol).await?;
Ok(conn)
}
}
impl crate::reconnect::ConnectionFactory for CredentialConnectionFactory {
fn connect(&self) -> Pin<Box<dyn Future<Output = Result<RedisConnection, RedisError>> + Send>> {
let factory = self.clone();
Box::pin(async move { factory.connect_inner().await })
}
}
impl crate::pool::PoolFactory for CredentialConnectionFactory {
type Connection = RedisConnection;
fn create(&self) -> Pin<Box<dyn Future<Output = Result<Self::Connection, RedisError>> + Send>> {
crate::reconnect::ConnectionFactory::connect(self)
}
}
pub async fn authenticate_with_refresh(
conn: &mut RedisConnection,
provider: &dyn CredentialProvider,
) -> Result<(), RedisError> {
let credentials = provider.get_credentials().await?;
match conn.execute(credentials.auth_command()).await {
Err(error) if is_auth_rejection(&error) => {
let credentials = provider.force_refresh().await?;
conn.execute(credentials.auth_command()).await
}
result => result,
}
}
pub fn is_auth_rejection(error: &RedisError) -> bool {
let RedisError::Redis(message) = error else {
return false;
};
message
.split_ascii_whitespace()
.next()
.map(|prefix| prefix.trim_start_matches('-'))
.is_some_and(|prefix| {
prefix.eq_ignore_ascii_case("NOAUTH") || prefix.eq_ignore_ascii_case("WRONGPASS")
})
}
pub struct AuthenticatedConnection<P> {
conn: RedisConnection,
provider: P,
}
impl<P: CredentialProvider> AuthenticatedConnection<P> {
pub async fn connect(addr: &str, provider: P) -> Result<Self, RedisError> {
let mut conn = RedisConnection::connect(addr).await?;
let creds = provider.get_credentials().await?;
conn.execute(creds.auth_command()).await?;
Ok(Self { conn, provider })
}
pub async fn connect_url(url: &str, provider: P) -> Result<Self, RedisError> {
let mut conn = RedisConnection::connect_url(url).await?;
let creds = provider.get_credentials().await?;
conn.execute(creds.auth_command()).await?;
Ok(Self { conn, provider })
}
pub async fn reauthenticate(&mut self) -> Result<(), RedisError> {
let creds = self.provider.get_credentials().await?;
self.conn.execute(creds.auth_command()).await
}
pub async fn execute<Cmd: Command>(&mut self, cmd: Cmd) -> Result<Cmd::Response, RedisError> {
self.conn.execute(cmd).await
}
pub fn provider(&self) -> &P {
&self.provider
}
pub fn connection_mut(&mut self) -> &mut RedisConnection {
&mut self.conn
}
}
pub struct RotatingAuthClient<P> {
conn: std::sync::Arc<tokio::sync::Mutex<RedisConnection>>,
provider: std::sync::Arc<P>,
timer_task: Option<tokio::task::JoinHandle<()>>,
_streaming_task: Option<CredentialReauthenticationHandle>,
}
impl<P: CredentialProvider> RotatingAuthClient<P> {
pub async fn connect(
addr: &str,
provider: P,
refresh_interval: std::time::Duration,
) -> Result<Self, RedisError> {
let mut conn = RedisConnection::connect(addr).await?;
let creds = provider.get_credentials().await?;
conn.execute(creds.auth_command()).await?;
let conn = std::sync::Arc::new(tokio::sync::Mutex::new(conn));
let provider = std::sync::Arc::new(provider);
let refresh_conn = conn.clone();
let refresh_provider = provider.clone();
let task = tokio::spawn(async move {
let mut interval = tokio::time::interval(refresh_interval);
interval.tick().await; loop {
interval.tick().await;
match refresh_provider.get_credentials().await {
Ok(creds) => {
let mut c = refresh_conn.lock().await;
let _ = c.execute(creds.auth_command()).await;
}
Err(_) => {
}
}
}
});
Ok(Self {
conn,
provider,
timer_task: Some(task),
_streaming_task: None,
})
}
pub async fn execute<Cmd: Command>(&self, cmd: Cmd) -> Result<Cmd::Response, RedisError> {
let mut conn = self.conn.lock().await;
conn.execute(cmd).await
}
pub fn provider(&self) -> &P {
&self.provider
}
}
impl<P> Drop for RotatingAuthClient<P> {
fn drop(&mut self) {
if let Some(task) = self.timer_task.take() {
task.abort();
}
}
}
impl<P: StreamingCredentialProvider> RotatingAuthClient<P> {
pub async fn connect_streaming(addr: &str, provider: P) -> Result<Self, RedisError> {
let mut conn = RedisConnection::connect(addr).await?;
let credentials = provider.get_credentials().await?;
conn.execute(credentials.auth_command()).await?;
let conn = Arc::new(tokio::sync::Mutex::new(conn));
let provider = Arc::new(provider);
let streaming_provider: Arc<dyn StreamingCredentialProvider> = provider.clone();
let refresh_conn = Arc::clone(&conn);
let streaming_task =
spawn_credential_reauthentication(streaming_provider, move |credentials| {
let refresh_conn = Arc::clone(&refresh_conn);
async move {
let mut conn = refresh_conn.lock().await;
conn.execute(credentials.auth_command()).await
}
});
Ok(Self {
conn,
provider,
timer_task: None,
_streaming_task: Some(streaming_task),
})
}
}
#[cfg(test)]
mod tests {
use super::*;
use redis_tower_protocol::helpers::{array, bulk};
use std::sync::atomic::{AtomicUsize, Ordering};
use zeroize::Zeroize;
struct RefreshAwareProvider {
get_calls: Arc<AtomicUsize>,
refresh_calls: Arc<AtomicUsize>,
}
struct OneShotStreamingProvider;
#[test]
fn credentials_zeroize_owned_material() {
let mut credentials = Credentials::new("alice", "secret-token");
credentials.zeroize();
assert!(credentials.username.is_none());
assert!(credentials.password.is_empty());
}
impl CredentialProvider for OneShotStreamingProvider {
fn get_credentials(
&self,
) -> Pin<Box<dyn Future<Output = Result<Credentials, RedisError>> + Send>> {
Box::pin(async { Ok(Credentials::password("initial")) })
}
}
impl StreamingCredentialProvider for OneShotStreamingProvider {
fn subscribe(self: Arc<Self>) -> CredentialUpdateStream {
Box::pin(futures::stream::once(async {
Ok(Credentials::password("pushed"))
}))
}
}
impl CredentialProvider for RefreshAwareProvider {
fn get_credentials(
&self,
) -> Pin<Box<dyn Future<Output = Result<Credentials, RedisError>> + Send>> {
self.get_calls.fetch_add(1, Ordering::SeqCst);
Box::pin(async { Ok(Credentials::password("cached")) })
}
fn force_refresh(
&self,
) -> Pin<Box<dyn Future<Output = Result<Credentials, RedisError>> + Send>> {
self.refresh_calls.fetch_add(1, Ordering::SeqCst);
Box::pin(async { Ok(Credentials::password("fresh")) })
}
}
#[test]
fn credentials_password_only() {
let creds = Credentials::password("secret");
assert!(creds.username.is_none());
assert_eq!(creds.password, "secret");
let auth = creds.auth_command();
let frame = auth.to_frame();
assert_eq!(frame, array(vec![bulk("AUTH"), bulk("secret")]));
}
#[test]
fn credentials_with_username() {
let creds = Credentials::new("admin", "pass123");
assert_eq!(creds.username.as_deref(), Some("admin"));
assert_eq!(creds.password, "pass123");
let auth = creds.auth_command();
let frame = auth.to_frame();
assert_eq!(
frame,
array(vec![bulk("AUTH"), bulk("admin"), bulk("pass123")])
);
}
#[test]
fn credentials_debug_redacts_password() {
let debug = format!("{:?}", Credentials::new("admin", "super-secret-token"));
assert!(debug.contains("admin"));
assert!(debug.contains("<redacted>"));
assert!(!debug.contains("super-secret-token"));
}
#[test]
fn static_credentials_password() {
let provider = StaticCredentials::password("token123");
let rt = tokio::runtime::Runtime::new().unwrap();
let creds = rt.block_on(provider.get_credentials()).unwrap();
assert_eq!(creds.password, "token123");
assert!(creds.username.is_none());
}
#[test]
fn static_credentials_with_user() {
let provider = StaticCredentials::new("user", "pass");
let rt = tokio::runtime::Runtime::new().unwrap();
let creds = rt.block_on(provider.get_credentials()).unwrap();
assert_eq!(creds.username.as_deref(), Some("user"));
assert_eq!(creds.password, "pass");
}
#[test]
fn closure_as_credential_provider() {
let provider = || async { Ok(Credentials::password("dynamic_token")) };
let rt = tokio::runtime::Runtime::new().unwrap();
let creds = rt.block_on(provider.get_credentials()).unwrap();
assert_eq!(creds.password, "dynamic_token");
}
#[test]
fn force_refresh_defaults_to_another_get() {
let calls = Arc::new(AtomicUsize::new(0));
let provider = {
let calls = Arc::clone(&calls);
move || {
calls.fetch_add(1, Ordering::SeqCst);
async { Ok(Credentials::password("fresh")) }
}
};
let rt = tokio::runtime::Runtime::new().unwrap();
let credentials = rt.block_on(provider.force_refresh()).unwrap();
assert_eq!(credentials.password, "fresh");
assert_eq!(calls.load(Ordering::SeqCst), 1);
}
#[test]
fn force_refresh_is_object_safe_and_overridable() {
let get_calls = Arc::new(AtomicUsize::new(0));
let refresh_calls = Arc::new(AtomicUsize::new(0));
let provider: Arc<dyn CredentialProvider> = Arc::new(RefreshAwareProvider {
get_calls: Arc::clone(&get_calls),
refresh_calls: Arc::clone(&refresh_calls),
});
let factory = CredentialConnectionFactory::from_shared_provider("localhost:6379", provider);
let rt = tokio::runtime::Runtime::new().unwrap();
let credentials = rt.block_on(factory.provider().force_refresh()).unwrap();
assert_eq!(credentials.password, "fresh");
assert_eq!(get_calls.load(Ordering::SeqCst), 0);
assert_eq!(refresh_calls.load(Ordering::SeqCst), 1);
}
#[test]
fn auth_rejection_classification_is_specific() {
assert!(is_auth_rejection(&RedisError::Redis(
"WRONGPASS invalid username-password pair".into()
)));
assert!(is_auth_rejection(&RedisError::Redis(
"NOAUTH Authentication required".into()
)));
assert!(is_auth_rejection(&RedisError::Redis(
"-wrongpass stale token".into()
)));
assert!(!is_auth_rejection(&RedisError::Redis(
"ERR invalid password policy".into()
)));
assert!(!is_auth_rejection(&RedisError::ConnectionClosed));
}
#[test]
fn credential_factory_implements_connection_and_pool_factories() {
fn assert_connection_factory<T: crate::reconnect::ConnectionFactory>() {}
fn assert_pool_factory<T: crate::pool::PoolFactory<Connection = RedisConnection>>() {}
fn assert_send_sync<T: Send + Sync>() {}
assert_connection_factory::<CredentialConnectionFactory>();
assert_pool_factory::<CredentialConnectionFactory>();
assert_send_sync::<CredentialConnectionFactory>();
}
#[tokio::test]
async fn push_helper_applies_emitted_credentials_and_shuts_down() {
let provider: Arc<dyn StreamingCredentialProvider> = Arc::new(OneShotStreamingProvider);
let applied = Arc::new(tokio::sync::Notify::new());
let observed = Arc::new(std::sync::Mutex::new(None));
let handle = spawn_credential_reauthentication(provider, {
let applied = Arc::clone(&applied);
let observed = Arc::clone(&observed);
move |credentials| {
let applied = Arc::clone(&applied);
let observed = Arc::clone(&observed);
async move {
*observed.lock().unwrap() = Some(credentials.password.clone());
applied.notify_one();
Ok(())
}
}
});
tokio::time::timeout(std::time::Duration::from_secs(1), applied.notified())
.await
.expect("pushed credential was not applied");
assert_eq!(observed.lock().unwrap().as_deref(), Some("pushed"));
handle.shutdown().await;
}
#[test]
fn credentials_clone() {
let creds = Credentials::new("u", "p");
let cloned = creds.clone();
assert_eq!(cloned.username, creds.username);
assert_eq!(cloned.password, creds.password);
}
#[test]
fn rotating_auth_client_types_compile() {
fn _assert_send<T: Send>() {}
_assert_send::<RotatingAuthClient<StaticCredentials>>();
}
#[test]
fn rotating_auth_client_drop_aborts_task() {
let _provider = StaticCredentials::password("token");
}
}