Skip to main content

redis_tower/
credentials.rs

1//! Dynamic credential provider for token rotation and cloud auth.
2//!
3//! Implement [`CredentialProvider`] to supply credentials dynamically,
4//! e.g., from AWS IAM, Azure Entra ID, or a secrets manager. The
5//! [`CredentialConnectionFactory`] fetches credentials for every fresh
6//! connection and composes with reconnecting clients and connection pools.
7//! URL-backed factories preserve transport, database, and protocol setup, and
8//! [`SharedCredentialProvider`] lets type-erased clients share one provider
9//! cache across ordinary, Cluster, Pub/Sub, and MONITOR connection owners.
10//! [`AuthenticatedConnection`] remains available for direct, manually managed
11//! connections.
12//!
13//! In-place reauthentication is only appropriate for owners that explicitly
14//! serialize it, such as multiplexed clients and retained pools. Pub/Sub and
15//! MONITOR owners reconnect or terminate at credential-update boundaries; see
16//! the [cloud authentication guide] for the complete session matrix.
17//!
18//! [cloud authentication guide]: https://github.com/joshrotenberg/redis-tower/blob/main/docs/CLOUD-AUTH.md
19//!
20//! # Example
21//!
22//! ```no_run
23//! use std::future::Future;
24//! use std::pin::Pin;
25//! use redis_tower::credentials::{
26//!     AuthenticatedConnection, CredentialProvider, Credentials, StaticCredentials,
27//! };
28//! use redis_tower::commands::Ping;
29//! use redis_tower::RedisError;
30//!
31//! # async fn fetch_iam_token() -> Result<String, RedisError> { Ok("token".into()) }
32//! # async fn example() -> Result<(), Box<dyn std::error::Error>> {
33//! // Static credentials (simple case).
34//! let creds = StaticCredentials::password("my_secret");
35//! let mut conn = AuthenticatedConnection::connect("127.0.0.1:6379", creds).await?;
36//! conn.execute(Ping::new()).await?;
37//!
38//! // Dynamic credentials (cloud IAM). This direct wrapper fetches once on
39//! // connect and again whenever reauthenticate() is called explicitly.
40//! struct IamProvider;
41//! impl CredentialProvider for IamProvider {
42//!     fn get_credentials(
43//!         &self,
44//!     ) -> Pin<Box<dyn Future<Output = Result<Credentials, RedisError>> + Send>> {
45//!         // Fetch a short-lived token from an IAM service.
46//!         Box::pin(async { Ok(Credentials::new("default", fetch_iam_token().await?)) })
47//!     }
48//! }
49//! let mut conn = AuthenticatedConnection::connect("127.0.0.1:6379", IamProvider).await?;
50//! conn.reauthenticate().await?;
51//! # Ok(())
52//! # }
53//! ```
54
55use std::fmt;
56use std::future::Future;
57use std::pin::Pin;
58use std::sync::Arc;
59use std::time::Duration;
60
61use futures::{Stream, StreamExt};
62use redis_tower_commands::Auth;
63use redis_tower_core::{Command, ConnectionConfig, ProtocolVersion, RedisConnection, RedisError};
64use tokio_util::sync::CancellationToken;
65
66/// A push stream of fresh credentials.
67///
68/// Providers yield only after the credentials used by an established
69/// connection have changed. Each item is either the replacement credentials
70/// or a refresh error. Providers must apply their own retry delay after an
71/// error so consumers cannot enter a busy loop.
72pub type CredentialUpdateStream =
73    Pin<Box<dyn Stream<Item = Result<Credentials, RedisError>> + Send + 'static>>;
74
75/// Credentials for Redis authentication.
76#[derive(Clone, zeroize::Zeroize, zeroize::ZeroizeOnDrop)]
77pub struct Credentials {
78    /// Optional username (Redis 6+ ACL). `None` for password-only auth.
79    pub username: Option<String>,
80    /// Password or auth token.
81    pub password: String,
82}
83
84impl fmt::Debug for Credentials {
85    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
86        formatter
87            .debug_struct("Credentials")
88            .field("username", &self.username.as_deref())
89            .field("password", &"<redacted>")
90            .finish()
91    }
92}
93
94impl Credentials {
95    /// Create credentials with username and password (Redis 6+ ACL).
96    pub fn new(username: impl Into<String>, password: impl Into<String>) -> Self {
97        Self {
98            username: Some(username.into()),
99            password: password.into(),
100        }
101    }
102
103    /// Create credentials with password only (legacy AUTH).
104    pub fn password(password: impl Into<String>) -> Self {
105        Self {
106            username: None,
107            password: password.into(),
108        }
109    }
110
111    /// Return the ACL username, if this is a two-argument credential.
112    pub fn username(&self) -> Option<&str> {
113        self.username.as_deref()
114    }
115
116    /// Return the password or short-lived auth token.
117    ///
118    /// Treat the returned value as secret material. It is borrowed so callers
119    /// do not create an additional plaintext allocation merely to authenticate.
120    pub fn password_value(&self) -> &str {
121        &self.password
122    }
123
124    /// Build the typed Redis `AUTH` command for these credentials.
125    ///
126    /// This is primarily useful when applying a value from a
127    /// [`CredentialUpdateStream`] to an established client.
128    pub fn auth_command(&self) -> Auth {
129        match &self.username {
130            Some(user) => Auth::credentials(user, &self.password),
131            None => Auth::password(&self.password),
132        }
133    }
134}
135
136/// Trait for providing credentials dynamically.
137///
138/// Implement this for cloud auth providers (AWS IAM, Azure Entra ID),
139/// secrets managers, or any source of rotating credentials.
140pub trait CredentialProvider: Send + Sync + 'static {
141    /// Fetch current credentials.
142    ///
143    /// [`CredentialConnectionFactory`] calls this for the initial connection
144    /// and every reconnect. Direct wrappers call it when connecting or when
145    /// reauthentication is requested. Implementations should handle caching
146    /// internally.
147    fn get_credentials(
148        &self,
149    ) -> Pin<Box<dyn Future<Output = Result<Credentials, RedisError>> + Send>>;
150
151    /// Force a fresh credential fetch after Redis rejects cached credentials.
152    ///
153    /// Providers that cache credentials should override this method to
154    /// invalidate or bypass that cache. The default calls
155    /// [`get_credentials`](Self::get_credentials) again, preserving the
156    /// existing behavior of simple providers and closures.
157    /// Calls may be concurrent across factory-backed clients or pool slots, so
158    /// caching providers must synchronize cache invalidation and refetching.
159    fn force_refresh(
160        &self,
161    ) -> Pin<Box<dyn Future<Output = Result<Credentials, RedisError>> + Send>> {
162        self.get_credentials()
163    }
164}
165
166/// A credential provider that can push replacements for established sockets.
167///
168/// Implementations return an independent stream for each subscription. The
169/// first item must represent a credential newer than the one used during the
170/// connection's initial [`CredentialProvider::get_credentials`] call. The
171/// `Arc<Self>` receiver lets the stream retain the provider without requiring
172/// the concrete type to be `Clone` and keeps the trait object-safe.
173pub trait StreamingCredentialProvider: CredentialProvider {
174    /// Subscribe to future credential replacements.
175    fn subscribe(self: Arc<Self>) -> CredentialUpdateStream;
176}
177
178/// Cloneable ownership handle for one shared credential-provider instance.
179///
180/// The wrapper delegates to an `Arc<P>` and itself implements
181/// [`CredentialProvider`]. When `P` also implements
182/// [`StreamingCredentialProvider`], the wrapper implements that trait too.
183/// This lets a type-erased host pass one provider cache to standalone,
184/// Cluster, pool, Pub/Sub, and MONITOR connection factories without requiring
185/// every builder to expose an `Arc<dyn ...>` overload.
186///
187/// # Example
188///
189/// ```no_run
190/// use std::sync::Arc;
191/// use redis_tower::credentials::{
192///     CredentialProvider, Credentials, SharedCredentialProvider,
193/// };
194/// use redis_tower::RedisError;
195///
196/// let provider: Arc<dyn CredentialProvider> = Arc::new(|| async {
197///     Ok::<_, RedisError>(Credentials::password("short-lived-token"))
198/// });
199/// let shared = SharedCredentialProvider::from_arc(provider);
200/// let standalone = shared.clone();
201/// let dedicated_session = shared;
202/// # let _ = (standalone, dedicated_session);
203/// ```
204pub struct SharedCredentialProvider<P: ?Sized = dyn CredentialProvider> {
205    inner: Arc<P>,
206}
207
208impl<P: ?Sized> Clone for SharedCredentialProvider<P> {
209    fn clone(&self) -> Self {
210        Self {
211            inner: Arc::clone(&self.inner),
212        }
213    }
214}
215
216impl<P: ?Sized> fmt::Debug for SharedCredentialProvider<P> {
217    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
218        formatter
219            .debug_struct("SharedCredentialProvider")
220            .finish_non_exhaustive()
221    }
222}
223
224impl<P> SharedCredentialProvider<P> {
225    /// Wrap a concrete provider in shared ownership.
226    pub fn new(provider: P) -> Self {
227        Self {
228            inner: Arc::new(provider),
229        }
230    }
231}
232
233impl<P: ?Sized> SharedCredentialProvider<P> {
234    /// Wrap an existing shared, possibly type-erased provider.
235    pub fn from_arc(provider: Arc<P>) -> Self {
236        Self { inner: provider }
237    }
238
239    /// Borrow the shared provider allocation.
240    pub fn as_arc(&self) -> &Arc<P> {
241        &self.inner
242    }
243
244    /// Return a clone of the shared provider allocation.
245    pub fn clone_arc(&self) -> Arc<P> {
246        Arc::clone(&self.inner)
247    }
248
249    /// Consume the handle and return the shared provider allocation.
250    pub fn into_arc(self) -> Arc<P> {
251        self.inner
252    }
253}
254
255impl<P: CredentialProvider + ?Sized> CredentialProvider for SharedCredentialProvider<P> {
256    fn get_credentials(
257        &self,
258    ) -> Pin<Box<dyn Future<Output = Result<Credentials, RedisError>> + Send>> {
259        self.inner.get_credentials()
260    }
261
262    fn force_refresh(
263        &self,
264    ) -> Pin<Box<dyn Future<Output = Result<Credentials, RedisError>> + Send>> {
265        self.inner.force_refresh()
266    }
267}
268
269impl<P: StreamingCredentialProvider + ?Sized> StreamingCredentialProvider
270    for SharedCredentialProvider<P>
271{
272    fn subscribe(self: Arc<Self>) -> CredentialUpdateStream {
273        Arc::clone(&self.inner).subscribe()
274    }
275}
276
277/// Owned task that applies credentials emitted by a streaming provider.
278///
279/// Dropping the handle cancels the subscription. Call [`shutdown`](Self::shutdown)
280/// to cancel it and wait for the task to finish. The task logs provider and
281/// reauthentication errors and keeps consuming later updates; it never
282/// replays a user command.
283#[must_use = "dropping the handle stops push-based credential reauthentication"]
284pub struct CredentialReauthenticationHandle {
285    cancellation: CancellationToken,
286    task: Option<tokio::task::JoinHandle<()>>,
287}
288
289impl CredentialReauthenticationHandle {
290    fn new(cancellation: CancellationToken, task: tokio::task::JoinHandle<()>) -> Self {
291        Self {
292            cancellation,
293            task: Some(task),
294        }
295    }
296
297    /// Stop consuming credential updates and wait for the task to exit.
298    pub async fn shutdown(mut self) {
299        self.cancellation.cancel();
300        if let Some(task) = self.task.take() {
301            let _ = task.await;
302        }
303    }
304}
305
306impl Drop for CredentialReauthenticationHandle {
307    fn drop(&mut self) {
308        self.cancellation.cancel();
309        if let Some(task) = self.task.take() {
310            task.abort();
311        }
312    }
313}
314
315/// Start applying pushed credentials with an asynchronous callback.
316///
317/// Use this only for a target that explicitly supports in-place `AUTH`, such as
318/// a normal multiplexed client or retained connection pool. Pub/Sub and
319/// MONITOR sockets are in dedicated protocol modes, while transactions and
320/// blocking calls can carry connection-local state; those owners should
321/// reconnect or terminate at a safe boundary instead. The callback must never
322/// retry a user command after an authentication error.
323pub fn spawn_credential_reauthentication<F, Fut>(
324    provider: Arc<dyn StreamingCredentialProvider>,
325    reauthenticate: F,
326) -> CredentialReauthenticationHandle
327where
328    F: Fn(Credentials) -> Fut + Send + Sync + 'static,
329    Fut: Future<Output = Result<(), RedisError>> + Send + 'static,
330{
331    let mut updates = Arc::clone(&provider).subscribe();
332    let cancellation = CancellationToken::new();
333    let task_cancellation = cancellation.clone();
334    let task = tokio::spawn(async move {
335        loop {
336            let update = tokio::select! {
337                () = task_cancellation.cancelled() => break,
338                update = updates.next() => update,
339            };
340            let Some(update) = update else {
341                break;
342            };
343            match update {
344                Ok(credentials) => {
345                    if reauthenticate(credentials).await.is_err() {
346                        // The callback may wrap a provider or server error.
347                        // Never render it here: third-party errors are not
348                        // guaranteed to redact credential material.
349                        tracing::warn!("credential reauthentication failed");
350                    }
351                }
352                Err(_error) => {
353                    // Provider errors can contain SDK request details. Keep
354                    // tracing useful without risking token disclosure.
355                    tracing::warn!("credential refresh stream failed");
356                }
357            }
358        }
359    });
360    CredentialReauthenticationHandle::new(cancellation, task)
361}
362
363/// A simple provider that always returns the same credentials.
364#[derive(Debug, Clone)]
365pub struct StaticCredentials {
366    creds: Credentials,
367}
368
369impl StaticCredentials {
370    /// Create a static provider with username and password.
371    pub fn new(username: impl Into<String>, password: impl Into<String>) -> Self {
372        Self {
373            creds: Credentials::new(username, password),
374        }
375    }
376
377    /// Create a static provider with password only.
378    pub fn password(password: impl Into<String>) -> Self {
379        Self {
380            creds: Credentials::password(password),
381        }
382    }
383}
384
385impl CredentialProvider for StaticCredentials {
386    fn get_credentials(
387        &self,
388    ) -> Pin<Box<dyn Future<Output = Result<Credentials, RedisError>> + Send>> {
389        let creds = self.creds.clone();
390        Box::pin(async move { Ok(creds) })
391    }
392}
393
394/// Blanket impl for closures.
395impl<F, Fut> CredentialProvider for F
396where
397    F: Fn() -> Fut + Send + Sync + 'static,
398    Fut: Future<Output = Result<Credentials, RedisError>> + Send + 'static,
399{
400    fn get_credentials(
401        &self,
402    ) -> Pin<Box<dyn Future<Output = Result<Credentials, RedisError>> + Send>> {
403        Box::pin((self)())
404    }
405}
406
407/// A provider-backed factory for authenticated Redis connections.
408///
409/// Every call fetches credentials, authenticates the fresh connection, and
410/// then negotiates the requested RESP protocol. This setup order matters for
411/// protected servers: negotiating RESP3 before `AUTH` can produce `NOAUTH`
412/// and leave an automatic negotiation silently on RESP2.
413///
414/// If Redis rejects the first `AUTH` with `NOAUTH` or `WRONGPASS`, the factory
415/// asks the provider to [`force_refresh`](CredentialProvider::force_refresh)
416/// and retries `AUTH` once. It never retries user commands.
417///
418/// The factory implements both
419/// [`ConnectionFactory`](crate::reconnect::ConnectionFactory) and
420/// [`PoolFactory`](crate::pool::PoolFactory), so the same setup is replayed by
421/// resilient, multiplexed, lazy, and replacement pool connections.
422/// [`from_url`](Self::from_url) additionally preserves URL transport, database,
423/// and protocol settings while replacing only URL-embedded authentication with
424/// the provider.
425///
426/// # Example
427///
428/// ```no_run
429/// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
430/// use redis_tower::credentials::{CredentialConnectionFactory, StaticCredentials};
431/// use redis_tower::reconnect::{ReconnectConfig, ResilientConnection};
432///
433/// let factory = CredentialConnectionFactory::new(
434///     "127.0.0.1:6379",
435///     StaticCredentials::password("secret"),
436/// );
437/// let connection = ResilientConnection::new(factory, ReconnectConfig::default()).await?;
438/// # let _ = connection;
439/// # Ok(())
440/// # }
441/// ```
442#[must_use = "a credential connection factory must be passed to a client or pool"]
443pub struct CredentialConnectionFactory {
444    target: CredentialTarget,
445    provider: Arc<dyn CredentialProvider>,
446    connection_config: ConnectionConfig,
447    setup_timeout: Option<Duration>,
448    #[cfg(any(feature = "tls-rustls", feature = "tls-native-tls"))]
449    tls: Option<(String, Arc<redis_tower_core::tls::TlsConfig>)>,
450}
451
452#[derive(Clone)]
453enum CredentialTarget {
454    Address(String),
455    Url(String),
456}
457
458impl Clone for CredentialConnectionFactory {
459    fn clone(&self) -> Self {
460        Self {
461            target: self.target.clone(),
462            provider: Arc::clone(&self.provider),
463            connection_config: self.connection_config.clone(),
464            setup_timeout: self.setup_timeout,
465            #[cfg(any(feature = "tls-rustls", feature = "tls-native-tls"))]
466            tls: self.tls.clone(),
467        }
468    }
469}
470
471impl CredentialConnectionFactory {
472    /// Create a plain-TCP factory backed by `provider`.
473    pub fn new(addr: impl Into<String>, provider: impl CredentialProvider) -> Self {
474        Self::from_shared_provider(addr, Arc::new(provider))
475    }
476
477    /// Create a plain-TCP factory from a shared, type-erased provider.
478    ///
479    /// This constructor lets several topology or pool factories share one
480    /// provider cache and refresh state.
481    pub fn from_shared_provider(
482        addr: impl Into<String>,
483        provider: Arc<dyn CredentialProvider>,
484    ) -> Self {
485        Self {
486            target: CredentialTarget::Address(addr.into()),
487            provider,
488            connection_config: ConnectionConfig::default(),
489            setup_timeout: None,
490            #[cfg(any(feature = "tls-rustls", feature = "tls-native-tls"))]
491            tls: None,
492        }
493    }
494
495    /// Create a URL-backed factory that authenticates with `provider`.
496    ///
497    /// TCP, TLS, Unix-socket, database, and `protocol` URL settings are
498    /// preserved. Any username or password embedded in the URL is ignored;
499    /// the provider is the single authentication source. Use
500    /// [`RedisConnection::connect_url`] when static URL credentials are
501    /// desired instead.
502    pub fn from_url(url: impl Into<String>, provider: impl CredentialProvider) -> Self {
503        Self::from_url_with_shared_provider(url, Arc::new(provider))
504    }
505
506    /// Create a URL-backed factory from a shared, type-erased provider.
507    pub fn from_url_with_shared_provider(
508        url: impl Into<String>,
509        provider: Arc<dyn CredentialProvider>,
510    ) -> Self {
511        Self {
512            target: CredentialTarget::Url(url.into()),
513            provider,
514            connection_config: ConnectionConfig::default(),
515            setup_timeout: None,
516            #[cfg(any(feature = "tls-rustls", feature = "tls-native-tls"))]
517            tls: None,
518        }
519    }
520
521    /// Apply connection settings to every initial connection and reconnect.
522    ///
523    /// Keepalive, connect timeout, and RESP decode limits apply during the
524    /// initial RESP2 bootstrap. The requested protocol is negotiated only
525    /// after authentication succeeds.
526    pub fn with_connection_config(mut self, config: ConnectionConfig) -> Self {
527        self.connection_config = config;
528        self
529    }
530
531    /// Bound the complete provider-backed setup sequence.
532    ///
533    /// Unlike [`ConnectionConfig::connect_timeout`], which covers only the
534    /// socket connect operation, this deadline includes credential lookup,
535    /// transport and TLS establishment, bounded refresh-on-rejection, database
536    /// selection, and RESP negotiation. Expiry returns
537    /// [`RedisError::ConnectTimeout`] and drops the partial socket.
538    pub fn with_setup_timeout(mut self, timeout: Duration) -> Self {
539        self.setup_timeout = Some(timeout);
540        self
541    }
542
543    /// Use explicit TLS settings for every connection made by this factory.
544    ///
545    /// For address targets, `hostname` is the server name used for certificate
546    /// verification. URL targets use the URL host, matching
547    /// [`RedisConnection::connect_url_with_tls`].
548    #[cfg(any(feature = "tls-rustls", feature = "tls-native-tls"))]
549    pub fn with_tls(
550        mut self,
551        hostname: impl Into<String>,
552        tls: redis_tower_core::tls::TlsConfig,
553    ) -> Self {
554        self.tls = Some((hostname.into(), Arc::new(tls)));
555        self
556    }
557
558    /// Return the shared credential provider used by this factory.
559    pub fn provider(&self) -> &dyn CredentialProvider {
560        self.provider.as_ref()
561    }
562
563    /// Clone the shared provider allocation used by this factory.
564    ///
565    /// This is useful when one type-erased provider must also be passed to a
566    /// Cluster builder or a dedicated-session factory.
567    pub fn shared_provider(&self) -> Arc<dyn CredentialProvider> {
568        Arc::clone(&self.provider)
569    }
570
571    async fn connect_inner(&self) -> Result<RedisConnection, RedisError> {
572        match self.setup_timeout {
573            Some(timeout) => tokio::time::timeout(timeout, self.connect_unbounded())
574                .await
575                .map_err(|_elapsed| RedisError::ConnectTimeout)?,
576            None => self.connect_unbounded().await,
577        }
578    }
579
580    async fn connect_unbounded(&self) -> Result<RedisConnection, RedisError> {
581        let requested_protocol = self.connection_config.protocol();
582        let bootstrap_config = self
583            .connection_config
584            .clone()
585            .with_protocol(ProtocolVersion::Resp2);
586
587        #[cfg(any(feature = "tls-rustls", feature = "tls-native-tls"))]
588        {
589            match &self.target {
590                CredentialTarget::Address(addr) => {
591                    let mut connection = match &self.tls {
592                        Some((hostname, tls)) => {
593                            RedisConnection::connect_tls_with_config(
594                                addr,
595                                hostname,
596                                tls.as_ref(),
597                                &bootstrap_config,
598                            )
599                            .await?
600                        }
601                        None => {
602                            RedisConnection::connect_with_config(addr, &bootstrap_config).await?
603                        }
604                    };
605                    authenticate_with_refresh(&mut connection, self.provider.as_ref()).await?;
606                    connection.negotiate_protocol(requested_protocol).await?;
607                    Ok(connection)
608                }
609                CredentialTarget::Url(url) => {
610                    let mut pending = match &self.tls {
611                        Some((_hostname, tls)) => {
612                            RedisConnection::begin_url_connection_with_tls_and_config(
613                                url,
614                                tls.as_ref(),
615                                &self.connection_config,
616                            )
617                            .await?
618                        }
619                        None => {
620                            RedisConnection::begin_url_connection_with_config(
621                                url,
622                                &self.connection_config,
623                            )
624                            .await?
625                        }
626                    };
627                    authenticate_with_refresh(pending.connection_mut(), self.provider.as_ref())
628                        .await?;
629                    pending.finish().await
630                }
631            }
632        }
633        #[cfg(not(any(feature = "tls-rustls", feature = "tls-native-tls")))]
634        {
635            match &self.target {
636                CredentialTarget::Address(addr) => {
637                    let mut connection =
638                        RedisConnection::connect_with_config(addr, &bootstrap_config).await?;
639                    authenticate_with_refresh(&mut connection, self.provider.as_ref()).await?;
640                    connection.negotiate_protocol(requested_protocol).await?;
641                    Ok(connection)
642                }
643                CredentialTarget::Url(url) => {
644                    let mut pending = RedisConnection::begin_url_connection_with_config(
645                        url,
646                        &self.connection_config,
647                    )
648                    .await?;
649                    authenticate_with_refresh(pending.connection_mut(), self.provider.as_ref())
650                        .await?;
651                    pending.finish().await
652                }
653            }
654        }
655    }
656}
657
658impl crate::reconnect::ConnectionFactory for CredentialConnectionFactory {
659    fn connect(&self) -> Pin<Box<dyn Future<Output = Result<RedisConnection, RedisError>> + Send>> {
660        let factory = self.clone();
661        Box::pin(async move { factory.connect_inner().await })
662    }
663}
664
665impl crate::pool::PoolFactory for CredentialConnectionFactory {
666    type Connection = RedisConnection;
667
668    fn create(&self) -> Pin<Box<dyn Future<Output = Result<Self::Connection, RedisError>> + Send>> {
669        crate::reconnect::ConnectionFactory::connect(self)
670    }
671}
672
673/// Authenticate one freshly opened connection and refresh once when Redis
674/// rejects cached credentials.
675///
676/// This helper is shared by standalone, Cluster, and Sentinel setup paths so
677/// every topology applies the same bounded retry rule. It is intended only for
678/// connection establishment; it never retries a user command.
679pub async fn authenticate_with_refresh(
680    conn: &mut RedisConnection,
681    provider: &dyn CredentialProvider,
682) -> Result<(), RedisError> {
683    let credentials = provider
684        .get_credentials()
685        .await
686        .map_err(|_error| credential_provider_failure("current credential lookup"))?;
687    match conn.execute(credentials.auth_command()).await {
688        Err(error) if is_auth_rejection(&error) => {
689            let credentials = provider
690                .force_refresh()
691                .await
692                .map_err(|_error| credential_provider_failure("forced refresh"))?;
693            conn.execute(credentials.auth_command()).await
694        }
695        result => result,
696    }
697}
698
699fn credential_provider_failure(operation: &'static str) -> RedisError {
700    // Never embed a third-party provider error. SDK errors can contain request
701    // details and custom providers may accidentally include token material.
702    RedisError::Redis(format!("AUTH_PROVIDER {operation} failed"))
703}
704
705/// Return whether Redis rejected authentication because credentials were
706/// missing or invalid.
707pub fn is_auth_rejection(error: &RedisError) -> bool {
708    let RedisError::Redis(message) = error else {
709        return false;
710    };
711    message
712        .split_ascii_whitespace()
713        .next()
714        .map(|prefix| prefix.trim_start_matches('-'))
715        .is_some_and(|prefix| {
716            prefix.eq_ignore_ascii_case("NOAUTH") || prefix.eq_ignore_ascii_case("WRONGPASS")
717        })
718}
719
720/// Return whether an error belongs to credential lookup or authentication.
721///
722/// This includes provider failures redacted by redis-tower as well as Redis
723/// `NOAUTH` and `WRONGPASS` replies. It is intended for downstream error
724/// classification without parsing full messages or exposing secret material.
725pub fn is_authentication_error(error: &RedisError) -> bool {
726    if is_auth_rejection(error) {
727        return true;
728    }
729    matches!(error, RedisError::Redis(message) if message.starts_with("AUTH_PROVIDER "))
730}
731
732/// A connection that authenticates using a [`CredentialProvider`].
733///
734/// Fetches credentials from the provider and sends AUTH after connecting.
735/// This direct wrapper does not reconnect automatically. Use
736/// [`CredentialConnectionFactory`] with a reconnecting client when credentials
737/// must be fetched again for every replacement connection.
738pub struct AuthenticatedConnection<P> {
739    conn: RedisConnection,
740    provider: P,
741}
742
743impl<P: CredentialProvider> AuthenticatedConnection<P> {
744    /// Connect and authenticate using the credential provider.
745    pub async fn connect(addr: &str, provider: P) -> Result<Self, RedisError> {
746        let mut conn = RedisConnection::connect(addr).await?;
747        authenticate_with_refresh(&mut conn, &provider).await?;
748        Ok(Self { conn, provider })
749    }
750
751    /// Connect via URL and authenticate with the provider.
752    ///
753    /// The URL transport, database, and protocol are preserved. URL-embedded
754    /// credentials are ignored so the provider remains the only credential
755    /// source.
756    pub async fn connect_url(url: &str, provider: P) -> Result<Self, RedisError> {
757        let mut pending =
758            RedisConnection::begin_url_connection_with_config(url, &ConnectionConfig::default())
759                .await?;
760        authenticate_with_refresh(pending.connection_mut(), &provider).await?;
761        let conn = pending.finish().await?;
762        Ok(Self { conn, provider })
763    }
764
765    /// Re-authenticate with fresh credentials from the provider.
766    ///
767    /// Call this when you receive an auth error or proactively before
768    /// token expiry.
769    pub async fn reauthenticate(&mut self) -> Result<(), RedisError> {
770        let creds = self
771            .provider
772            .get_credentials()
773            .await
774            .map_err(|_error| credential_provider_failure("reauthentication lookup"))?;
775        self.conn.execute(creds.auth_command()).await
776    }
777
778    /// Execute a command.
779    pub async fn execute<Cmd: Command>(&mut self, cmd: Cmd) -> Result<Cmd::Response, RedisError> {
780        self.conn.execute(cmd).await
781    }
782
783    /// Get a reference to the credential provider.
784    pub fn provider(&self) -> &P {
785        &self.provider
786    }
787
788    /// Get a mutable reference to the inner connection.
789    pub fn connection_mut(&mut self) -> &mut RedisConnection {
790        &mut self.conn
791    }
792}
793
794/// A connection that periodically refreshes credentials on a timer.
795///
796/// Wraps a [`RedisConnection`] in `Arc<Mutex<>>` and spawns a background
797/// tokio task that re-authenticates at `refresh_interval`. This is intended
798/// for cloud environments (AWS ElastiCache IAM, GCP MemoryStore) where
799/// credentials expire.
800///
801/// The refresh interval should be shorter than the token TTL to avoid
802/// authentication gaps.
803///
804/// # Example
805///
806/// ```no_run
807/// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
808/// use std::time::Duration;
809/// use redis_tower::credentials::{RotatingAuthClient, StaticCredentials};
810///
811/// let provider = StaticCredentials::password("token");
812/// let client = RotatingAuthClient::connect(
813///     "127.0.0.1:6379",
814///     provider,
815///     Duration::from_secs(300),
816/// ).await?;
817/// # let _ = client;
818/// # Ok(())
819/// # }
820/// ```
821pub struct RotatingAuthClient<P> {
822    conn: std::sync::Arc<tokio::sync::Mutex<RedisConnection>>,
823    provider: std::sync::Arc<P>,
824    timer_task: Option<tokio::task::JoinHandle<()>>,
825    _streaming_task: Option<CredentialReauthenticationHandle>,
826}
827
828impl<P: CredentialProvider> RotatingAuthClient<P> {
829    /// Connect, authenticate, and start background credential rotation.
830    ///
831    /// The background task re-authenticates every `refresh_interval`. If
832    /// credential fetch or AUTH fails, the error is logged (via `tracing`)
833    /// and the next tick retries.
834    pub async fn connect(
835        addr: &str,
836        provider: P,
837        refresh_interval: std::time::Duration,
838    ) -> Result<Self, RedisError> {
839        let mut conn = RedisConnection::connect(addr).await?;
840        authenticate_with_refresh(&mut conn, &provider).await?;
841
842        let conn = std::sync::Arc::new(tokio::sync::Mutex::new(conn));
843        let provider = std::sync::Arc::new(provider);
844
845        let refresh_conn = conn.clone();
846        let refresh_provider = provider.clone();
847        let task = tokio::spawn(async move {
848            let mut interval = tokio::time::interval(refresh_interval);
849            interval.tick().await; // skip first immediate tick
850            loop {
851                interval.tick().await;
852                match refresh_provider.get_credentials().await {
853                    Ok(creds) => {
854                        let mut c = refresh_conn.lock().await;
855                        let _ = c.execute(creds.auth_command()).await;
856                    }
857                    Err(_) => {
858                        // Best-effort: next tick will retry.
859                    }
860                }
861            }
862        });
863
864        Ok(Self {
865            conn,
866            provider,
867            timer_task: Some(task),
868            _streaming_task: None,
869        })
870    }
871
872    /// Execute a command on the underlying connection.
873    pub async fn execute<Cmd: Command>(&self, cmd: Cmd) -> Result<Cmd::Response, RedisError> {
874        let mut conn = self.conn.lock().await;
875        conn.execute(cmd).await
876    }
877
878    /// Get a reference to the credential provider.
879    pub fn provider(&self) -> &P {
880        &self.provider
881    }
882}
883
884impl<P> Drop for RotatingAuthClient<P> {
885    fn drop(&mut self) {
886        if let Some(task) = self.timer_task.take() {
887            task.abort();
888        }
889        // `CredentialReauthenticationHandle::drop` cancels and aborts the
890        // streaming task after this method returns.
891    }
892}
893
894impl<P: StreamingCredentialProvider> RotatingAuthClient<P> {
895    /// Connect, authenticate, and re-authenticate whenever `provider` emits.
896    ///
897    /// Unlike [`Self::connect`], this has no polling interval. The provider
898    /// controls refresh timing from the actual credential lifetime, and the
899    /// owned task stops when this client is dropped.
900    pub async fn connect_streaming(addr: &str, provider: P) -> Result<Self, RedisError> {
901        let mut conn = RedisConnection::connect(addr).await?;
902        authenticate_with_refresh(&mut conn, &provider).await?;
903
904        let conn = Arc::new(tokio::sync::Mutex::new(conn));
905        let provider = Arc::new(provider);
906        let streaming_provider: Arc<dyn StreamingCredentialProvider> = provider.clone();
907        let refresh_conn = Arc::clone(&conn);
908        let streaming_task =
909            spawn_credential_reauthentication(streaming_provider, move |credentials| {
910                let refresh_conn = Arc::clone(&refresh_conn);
911                async move {
912                    let mut conn = refresh_conn.lock().await;
913                    conn.execute(credentials.auth_command()).await
914                }
915            });
916
917        Ok(Self {
918            conn,
919            provider,
920            timer_task: None,
921            _streaming_task: Some(streaming_task),
922        })
923    }
924}
925
926#[cfg(test)]
927mod tests {
928    use super::*;
929    use redis_tower_protocol::helpers::{array, bulk};
930    use std::sync::Mutex;
931    use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
932    use tracing_subscriber::layer::{Context, Layer};
933    use tracing_subscriber::prelude::*;
934    use zeroize::Zeroize;
935
936    struct RefreshAwareProvider {
937        get_calls: Arc<AtomicUsize>,
938        refresh_calls: Arc<AtomicUsize>,
939    }
940
941    struct OneShotStreamingProvider;
942
943    struct LeakyStreamingProvider;
944
945    #[derive(Clone, Default)]
946    struct EventCapture {
947        events: Arc<Mutex<Vec<String>>>,
948    }
949
950    struct FieldCollector(String);
951
952    impl tracing::field::Visit for FieldCollector {
953        fn record_debug(&mut self, field: &tracing::field::Field, value: &dyn fmt::Debug) {
954            self.0.push_str(&format!(" {}={value:?}", field.name()));
955        }
956    }
957
958    impl<S: tracing::Subscriber> Layer<S> for EventCapture {
959        fn on_event(&self, event: &tracing::Event<'_>, _context: Context<'_, S>) {
960            let mut collector = FieldCollector(String::new());
961            event.record(&mut collector);
962            self.events.lock().unwrap().push(collector.0);
963        }
964    }
965
966    struct DropAwareStreamingProvider {
967        stream_created: Arc<tokio::sync::Notify>,
968        stream_dropped: Arc<AtomicBool>,
969    }
970
971    struct DropAwareStream {
972        created: Arc<tokio::sync::Notify>,
973        dropped: Arc<AtomicBool>,
974        announced: bool,
975    }
976
977    impl Stream for DropAwareStream {
978        type Item = Result<Credentials, RedisError>;
979
980        fn poll_next(
981            mut self: Pin<&mut Self>,
982            _context: &mut std::task::Context<'_>,
983        ) -> std::task::Poll<Option<Self::Item>> {
984            if !self.announced {
985                self.announced = true;
986                self.created.notify_one();
987            }
988            std::task::Poll::Pending
989        }
990    }
991
992    impl Drop for DropAwareStream {
993        fn drop(&mut self) {
994            self.dropped.store(true, Ordering::SeqCst);
995        }
996    }
997
998    #[test]
999    fn credentials_zeroize_owned_material() {
1000        let mut credentials = Credentials::new("alice", "secret-token");
1001        credentials.zeroize();
1002        assert!(credentials.username.is_none());
1003        assert!(credentials.password.is_empty());
1004    }
1005
1006    impl CredentialProvider for OneShotStreamingProvider {
1007        fn get_credentials(
1008            &self,
1009        ) -> Pin<Box<dyn Future<Output = Result<Credentials, RedisError>> + Send>> {
1010            Box::pin(async { Ok(Credentials::password("initial")) })
1011        }
1012    }
1013
1014    impl StreamingCredentialProvider for OneShotStreamingProvider {
1015        fn subscribe(self: Arc<Self>) -> CredentialUpdateStream {
1016            Box::pin(futures::stream::once(async {
1017                Ok(Credentials::password("pushed"))
1018            }))
1019        }
1020    }
1021
1022    impl CredentialProvider for DropAwareStreamingProvider {
1023        fn get_credentials(
1024            &self,
1025        ) -> Pin<Box<dyn Future<Output = Result<Credentials, RedisError>> + Send>> {
1026            Box::pin(async { Ok(Credentials::password("initial")) })
1027        }
1028    }
1029
1030    impl CredentialProvider for LeakyStreamingProvider {
1031        fn get_credentials(
1032            &self,
1033        ) -> Pin<Box<dyn Future<Output = Result<Credentials, RedisError>> + Send>> {
1034            Box::pin(async { Ok(Credentials::password("initial")) })
1035        }
1036    }
1037
1038    impl StreamingCredentialProvider for LeakyStreamingProvider {
1039        fn subscribe(self: Arc<Self>) -> CredentialUpdateStream {
1040            Box::pin(futures::stream::iter([
1041                Err(RedisError::Redis(
1042                    "provider-secret-must-not-be-traced".to_string(),
1043                )),
1044                Ok(Credentials::password("callback-input-secret")),
1045            ]))
1046        }
1047    }
1048
1049    impl StreamingCredentialProvider for DropAwareStreamingProvider {
1050        fn subscribe(self: Arc<Self>) -> CredentialUpdateStream {
1051            Box::pin(DropAwareStream {
1052                created: Arc::clone(&self.stream_created),
1053                dropped: Arc::clone(&self.stream_dropped),
1054                announced: false,
1055            })
1056        }
1057    }
1058
1059    impl CredentialProvider for RefreshAwareProvider {
1060        fn get_credentials(
1061            &self,
1062        ) -> Pin<Box<dyn Future<Output = Result<Credentials, RedisError>> + Send>> {
1063            self.get_calls.fetch_add(1, Ordering::SeqCst);
1064            Box::pin(async { Ok(Credentials::password("cached")) })
1065        }
1066
1067        fn force_refresh(
1068            &self,
1069        ) -> Pin<Box<dyn Future<Output = Result<Credentials, RedisError>> + Send>> {
1070            self.refresh_calls.fetch_add(1, Ordering::SeqCst);
1071            Box::pin(async { Ok(Credentials::password("fresh")) })
1072        }
1073    }
1074
1075    #[test]
1076    fn credentials_password_only() {
1077        let creds = Credentials::password("secret");
1078        assert!(creds.username.is_none());
1079        assert_eq!(creds.password, "secret");
1080
1081        let auth = creds.auth_command();
1082        let frame = auth.to_frame();
1083        assert_eq!(frame, array(vec![bulk("AUTH"), bulk("secret")]));
1084    }
1085
1086    #[test]
1087    fn credentials_with_username() {
1088        let creds = Credentials::new("admin", "pass123");
1089        assert_eq!(creds.username.as_deref(), Some("admin"));
1090        assert_eq!(creds.password, "pass123");
1091
1092        let auth = creds.auth_command();
1093        let frame = auth.to_frame();
1094        assert_eq!(
1095            frame,
1096            array(vec![bulk("AUTH"), bulk("admin"), bulk("pass123")])
1097        );
1098    }
1099
1100    #[test]
1101    fn credentials_debug_redacts_password() {
1102        let debug = format!("{:?}", Credentials::new("admin", "super-secret-token"));
1103        assert!(debug.contains("admin"));
1104        assert!(debug.contains("<redacted>"));
1105        assert!(!debug.contains("super-secret-token"));
1106    }
1107
1108    #[test]
1109    fn static_credentials_password() {
1110        let provider = StaticCredentials::password("token123");
1111        let rt = tokio::runtime::Runtime::new().unwrap();
1112        let creds = rt.block_on(provider.get_credentials()).unwrap();
1113        assert_eq!(creds.password, "token123");
1114        assert!(creds.username.is_none());
1115    }
1116
1117    #[test]
1118    fn static_credentials_with_user() {
1119        let provider = StaticCredentials::new("user", "pass");
1120        let rt = tokio::runtime::Runtime::new().unwrap();
1121        let creds = rt.block_on(provider.get_credentials()).unwrap();
1122        assert_eq!(creds.username.as_deref(), Some("user"));
1123        assert_eq!(creds.password, "pass");
1124    }
1125
1126    #[test]
1127    fn closure_as_credential_provider() {
1128        let provider = || async { Ok(Credentials::password("dynamic_token")) };
1129        let rt = tokio::runtime::Runtime::new().unwrap();
1130        let creds = rt.block_on(provider.get_credentials()).unwrap();
1131        assert_eq!(creds.password, "dynamic_token");
1132    }
1133
1134    #[test]
1135    fn force_refresh_defaults_to_another_get() {
1136        let calls = Arc::new(AtomicUsize::new(0));
1137        let provider = {
1138            let calls = Arc::clone(&calls);
1139            move || {
1140                calls.fetch_add(1, Ordering::SeqCst);
1141                async { Ok(Credentials::password("fresh")) }
1142            }
1143        };
1144
1145        let rt = tokio::runtime::Runtime::new().unwrap();
1146        let credentials = rt.block_on(provider.force_refresh()).unwrap();
1147
1148        assert_eq!(credentials.password, "fresh");
1149        assert_eq!(calls.load(Ordering::SeqCst), 1);
1150    }
1151
1152    #[test]
1153    fn force_refresh_is_object_safe_and_overridable() {
1154        let get_calls = Arc::new(AtomicUsize::new(0));
1155        let refresh_calls = Arc::new(AtomicUsize::new(0));
1156        let provider: Arc<dyn CredentialProvider> = Arc::new(RefreshAwareProvider {
1157            get_calls: Arc::clone(&get_calls),
1158            refresh_calls: Arc::clone(&refresh_calls),
1159        });
1160        let factory = CredentialConnectionFactory::from_shared_provider("localhost:6379", provider);
1161
1162        let rt = tokio::runtime::Runtime::new().unwrap();
1163        let credentials = rt.block_on(factory.provider().force_refresh()).unwrap();
1164
1165        assert_eq!(credentials.password, "fresh");
1166        assert_eq!(get_calls.load(Ordering::SeqCst), 0);
1167        assert_eq!(refresh_calls.load(Ordering::SeqCst), 1);
1168    }
1169
1170    #[test]
1171    fn shared_provider_handle_preserves_one_type_erased_provider() {
1172        let get_calls = Arc::new(AtomicUsize::new(0));
1173        let refresh_calls = Arc::new(AtomicUsize::new(0));
1174        let provider: Arc<dyn CredentialProvider> = Arc::new(RefreshAwareProvider {
1175            get_calls: Arc::clone(&get_calls),
1176            refresh_calls: Arc::clone(&refresh_calls),
1177        });
1178        let shared = SharedCredentialProvider::from_arc(provider);
1179        let first = shared.clone();
1180        let second = shared;
1181
1182        let rt = tokio::runtime::Runtime::new().unwrap();
1183        rt.block_on(async {
1184            first.get_credentials().await.unwrap();
1185            second.force_refresh().await.unwrap();
1186        });
1187
1188        assert_eq!(get_calls.load(Ordering::SeqCst), 1);
1189        assert_eq!(refresh_calls.load(Ordering::SeqCst), 1);
1190    }
1191
1192    #[tokio::test]
1193    async fn shared_streaming_provider_delegates_subscription() {
1194        let shared = SharedCredentialProvider::new(OneShotStreamingProvider);
1195        let shared: Arc<dyn StreamingCredentialProvider> = Arc::new(shared);
1196        let mut updates = Arc::clone(&shared).subscribe();
1197
1198        let credentials = updates.next().await.unwrap().unwrap();
1199        assert_eq!(credentials.password_value(), "pushed");
1200    }
1201
1202    #[test]
1203    fn auth_rejection_classification_is_specific() {
1204        assert!(is_auth_rejection(&RedisError::Redis(
1205            "WRONGPASS invalid username-password pair".into()
1206        )));
1207        assert!(is_auth_rejection(&RedisError::Redis(
1208            "NOAUTH Authentication required".into()
1209        )));
1210        assert!(is_auth_rejection(&RedisError::Redis(
1211            "-wrongpass stale token".into()
1212        )));
1213        assert!(!is_auth_rejection(&RedisError::Redis(
1214            "ERR invalid password policy".into()
1215        )));
1216        assert!(!is_auth_rejection(&RedisError::ConnectionClosed));
1217    }
1218
1219    #[test]
1220    fn provider_failure_is_authentication_classified_without_secret_material() {
1221        let error = credential_provider_failure("current credential lookup");
1222        let rendered = error.to_string();
1223        assert!(is_authentication_error(&error));
1224        assert!(rendered.contains("AUTH_PROVIDER"));
1225        assert!(!rendered.contains("token"));
1226    }
1227
1228    #[test]
1229    fn credential_factory_implements_connection_and_pool_factories() {
1230        fn assert_connection_factory<T: crate::reconnect::ConnectionFactory>() {}
1231        fn assert_pool_factory<T: crate::pool::PoolFactory<Connection = RedisConnection>>() {}
1232        fn assert_send_sync<T: Send + Sync>() {}
1233
1234        assert_connection_factory::<CredentialConnectionFactory>();
1235        assert_pool_factory::<CredentialConnectionFactory>();
1236        assert_send_sync::<CredentialConnectionFactory>();
1237    }
1238
1239    #[tokio::test]
1240    async fn push_helper_applies_emitted_credentials_and_shuts_down() {
1241        let provider: Arc<dyn StreamingCredentialProvider> = Arc::new(OneShotStreamingProvider);
1242        let applied = Arc::new(tokio::sync::Notify::new());
1243        let observed = Arc::new(std::sync::Mutex::new(None));
1244        let handle = spawn_credential_reauthentication(provider, {
1245            let applied = Arc::clone(&applied);
1246            let observed = Arc::clone(&observed);
1247            move |credentials| {
1248                let applied = Arc::clone(&applied);
1249                let observed = Arc::clone(&observed);
1250                async move {
1251                    *observed.lock().unwrap() = Some(credentials.password.clone());
1252                    applied.notify_one();
1253                    Ok(())
1254                }
1255            }
1256        });
1257
1258        tokio::time::timeout(std::time::Duration::from_secs(1), applied.notified())
1259            .await
1260            .expect("pushed credential was not applied");
1261        assert_eq!(observed.lock().unwrap().as_deref(), Some("pushed"));
1262        handle.shutdown().await;
1263    }
1264
1265    #[tokio::test]
1266    async fn dropping_push_handle_drops_provider_stream() {
1267        let stream_created = Arc::new(tokio::sync::Notify::new());
1268        let stream_dropped = Arc::new(AtomicBool::new(false));
1269        let provider: Arc<dyn StreamingCredentialProvider> = Arc::new(DropAwareStreamingProvider {
1270            stream_created: Arc::clone(&stream_created),
1271            stream_dropped: Arc::clone(&stream_dropped),
1272        });
1273        let handle = spawn_credential_reauthentication(provider, |_credentials| async { Ok(()) });
1274
1275        tokio::time::timeout(Duration::from_secs(1), stream_created.notified())
1276            .await
1277            .expect("provider stream was not polled");
1278        drop(handle);
1279        tokio::task::yield_now().await;
1280        assert!(
1281            stream_dropped.load(Ordering::SeqCst),
1282            "dropping the owner must stop and drop its refresh stream"
1283        );
1284    }
1285
1286    #[tokio::test]
1287    async fn push_helper_tracing_does_not_render_provider_or_callback_errors() {
1288        let capture = EventCapture::default();
1289        let subscriber = tracing_subscriber::registry().with(capture.clone());
1290        let _guard = tracing::subscriber::set_default(subscriber);
1291        let callback_reached = Arc::new(tokio::sync::Notify::new());
1292        let provider: Arc<dyn StreamingCredentialProvider> = Arc::new(LeakyStreamingProvider);
1293        let handle = spawn_credential_reauthentication(provider, {
1294            let callback_reached = Arc::clone(&callback_reached);
1295            move |_credentials| {
1296                callback_reached.notify_one();
1297                async {
1298                    Err(RedisError::Redis(
1299                        "callback-secret-must-not-be-traced".to_string(),
1300                    ))
1301                }
1302            }
1303        });
1304
1305        tokio::time::timeout(Duration::from_secs(1), callback_reached.notified())
1306            .await
1307            .expect("credential callback was not reached");
1308        handle.shutdown().await;
1309
1310        let events = capture.events.lock().unwrap().join("\n");
1311        assert!(events.contains("credential refresh stream failed"));
1312        assert!(events.contains("credential reauthentication failed"));
1313        assert!(!events.contains("provider-secret-must-not-be-traced"));
1314        assert!(!events.contains("callback-secret-must-not-be-traced"));
1315        assert!(!events.contains("callback-input-secret"));
1316    }
1317
1318    #[test]
1319    fn credentials_clone() {
1320        let creds = Credentials::new("u", "p");
1321        let cloned = creds.clone();
1322        assert_eq!(cloned.username, creds.username);
1323        assert_eq!(cloned.password, creds.password);
1324    }
1325
1326    // -- RotatingAuthClient --
1327
1328    #[test]
1329    fn rotating_auth_client_types_compile() {
1330        // Verify RotatingAuthClient can be constructed with StaticCredentials
1331        // (type-level check, no actual connection).
1332        fn _assert_send<T: Send>() {}
1333        _assert_send::<RotatingAuthClient<StaticCredentials>>();
1334    }
1335
1336    #[test]
1337    fn rotating_auth_client_drop_aborts_task() {
1338        // Verify that dropping a RotatingAuthClient does not panic.
1339        // We cannot construct one without a real connection, but we can
1340        // confirm the Drop impl compiles and the type is well-formed.
1341        let _provider = StaticCredentials::password("token");
1342        // Type assertion only -- actual connect needs a running Redis.
1343    }
1344}