1use 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
66pub type CredentialUpdateStream =
73 Pin<Box<dyn Stream<Item = Result<Credentials, RedisError>> + Send + 'static>>;
74
75#[derive(Clone, zeroize::Zeroize, zeroize::ZeroizeOnDrop)]
77pub struct Credentials {
78 pub username: Option<String>,
80 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 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 pub fn password(password: impl Into<String>) -> Self {
105 Self {
106 username: None,
107 password: password.into(),
108 }
109 }
110
111 pub fn username(&self) -> Option<&str> {
113 self.username.as_deref()
114 }
115
116 pub fn password_value(&self) -> &str {
121 &self.password
122 }
123
124 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
136pub trait CredentialProvider: Send + Sync + 'static {
141 fn get_credentials(
148 &self,
149 ) -> Pin<Box<dyn Future<Output = Result<Credentials, RedisError>> + Send>>;
150
151 fn force_refresh(
160 &self,
161 ) -> Pin<Box<dyn Future<Output = Result<Credentials, RedisError>> + Send>> {
162 self.get_credentials()
163 }
164}
165
166pub trait StreamingCredentialProvider: CredentialProvider {
174 fn subscribe(self: Arc<Self>) -> CredentialUpdateStream;
176}
177
178pub 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 pub fn new(provider: P) -> Self {
227 Self {
228 inner: Arc::new(provider),
229 }
230 }
231}
232
233impl<P: ?Sized> SharedCredentialProvider<P> {
234 pub fn from_arc(provider: Arc<P>) -> Self {
236 Self { inner: provider }
237 }
238
239 pub fn as_arc(&self) -> &Arc<P> {
241 &self.inner
242 }
243
244 pub fn clone_arc(&self) -> Arc<P> {
246 Arc::clone(&self.inner)
247 }
248
249 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#[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 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
315pub 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 tracing::warn!("credential reauthentication failed");
350 }
351 }
352 Err(_error) => {
353 tracing::warn!("credential refresh stream failed");
356 }
357 }
358 }
359 });
360 CredentialReauthenticationHandle::new(cancellation, task)
361}
362
363#[derive(Debug, Clone)]
365pub struct StaticCredentials {
366 creds: Credentials,
367}
368
369impl StaticCredentials {
370 pub fn new(username: impl Into<String>, password: impl Into<String>) -> Self {
372 Self {
373 creds: Credentials::new(username, password),
374 }
375 }
376
377 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
394impl<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#[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 pub fn new(addr: impl Into<String>, provider: impl CredentialProvider) -> Self {
474 Self::from_shared_provider(addr, Arc::new(provider))
475 }
476
477 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 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 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 pub fn with_connection_config(mut self, config: ConnectionConfig) -> Self {
527 self.connection_config = config;
528 self
529 }
530
531 pub fn with_setup_timeout(mut self, timeout: Duration) -> Self {
539 self.setup_timeout = Some(timeout);
540 self
541 }
542
543 #[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 pub fn provider(&self) -> &dyn CredentialProvider {
560 self.provider.as_ref()
561 }
562
563 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
673pub 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 RedisError::Redis(format!("AUTH_PROVIDER {operation} failed"))
703}
704
705pub 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
720pub 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
732pub struct AuthenticatedConnection<P> {
739 conn: RedisConnection,
740 provider: P,
741}
742
743impl<P: CredentialProvider> AuthenticatedConnection<P> {
744 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 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 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 pub async fn execute<Cmd: Command>(&mut self, cmd: Cmd) -> Result<Cmd::Response, RedisError> {
780 self.conn.execute(cmd).await
781 }
782
783 pub fn provider(&self) -> &P {
785 &self.provider
786 }
787
788 pub fn connection_mut(&mut self) -> &mut RedisConnection {
790 &mut self.conn
791 }
792}
793
794pub 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 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; 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 }
860 }
861 }
862 });
863
864 Ok(Self {
865 conn,
866 provider,
867 timer_task: Some(task),
868 _streaming_task: None,
869 })
870 }
871
872 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 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 }
892}
893
894impl<P: StreamingCredentialProvider> RotatingAuthClient<P> {
895 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 #[test]
1329 fn rotating_auth_client_types_compile() {
1330 fn _assert_send<T: Send>() {}
1333 _assert_send::<RotatingAuthClient<StaticCredentials>>();
1334 }
1335
1336 #[test]
1337 fn rotating_auth_client_drop_aborts_task() {
1338 let _provider = StaticCredentials::password("token");
1342 }
1344}