sz-rust-auth-facade 0.6.7

Auth facade for sz-rust framework — WeChat, OAuth2, Gateway
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
//! Redis 存储后端 — RedisRefreshTokenStore + RedisTokenBlacklist
//!
//! 对齐 spec.md FR-1 ~ FR-6,design.md §2.1 ~ §2.6。
//!
//! ## 核心组件
//!
//! - [`RedisConfig`]:Redis 连接配置(URL + key 前缀 + 超时),Debug 脱敏密码
//! - [`RedisRefreshTokenStore`]:实现 [`RefreshTokenStore`] trait(GET / INCR)
//! - [`RedisTokenBlacklist`]:实现 [`TokenBlacklist`] trait(EXISTS / SETEX)
//! - [`create_redis_stores`]:便捷工厂,一次创建 Store + Blacklist 共享 ConnectionManager

use crate::refresh::{
    DeviceInfo, DeviceSession, DeviceSessionStore, RefreshTokenError, RefreshTokenStore,
    TokenBlacklist,
};
use redis::aio::ConnectionManager;
use redis::AsyncCommands;
use std::fmt;
use std::time::Duration;

// ── RedisConfig ──

/// Redis 存储配置
///
/// 对齐 design.md §2.2。URL 中的密码在 Debug 输出时自动脱敏。
#[derive(Clone)]
pub struct RedisConfig {
    /// Redis 连接 URL(如 `redis://:password@127.0.0.1:6379/0`)
    pub url: String,
    /// 版本号 key 前缀(默认 `sso:ver`)
    pub key_prefix_ver: String,
    /// 黑名单 key 前缀(默认 `sso:bl`)
    pub key_prefix_bl: String,
    /// 设备会话 key 前缀(默认 `sso:sessions`)
    pub key_prefix_sessions: String,
    /// 连接超时(默认 3s)
    pub connection_timeout: Duration,
    /// 命令超时(默认 2s)
    pub command_timeout: Duration,
}

impl Default for RedisConfig {
    fn default() -> Self {
        Self {
            url: "redis://127.0.0.1:6379".to_string(),
            key_prefix_ver: "sso:ver".to_string(),
            key_prefix_bl: "sso:bl".to_string(),
            key_prefix_sessions: "sso:sessions".to_string(),
            connection_timeout: Duration::from_secs(3),
            command_timeout: Duration::from_secs(2),
        }
    }
}

impl RedisConfig {
    /// 从 URL 创建配置,其余字段使用默认值
    pub fn from_url(url: impl Into<String>) -> Self {
        Self {
            url: url.into(),
            ..Default::default()
        }
    }

    /// 构造版本号 key:`{prefix}:{user_id}`
    fn ver_key(&self, user_id: i64) -> String {
        format!("{}:{}", self.key_prefix_ver, user_id)
    }

    /// 构造黑名单 key:`{prefix}:{jti}`
    fn bl_key(&self, jti: &str) -> String {
        format!("{}:{}", self.key_prefix_bl, jti)
    }

    /// 构造设备会话 key:`{prefix}:{user_id}`
    fn sessions_key(&self, user_id: i64) -> String {
        format!("{}:{}", self.key_prefix_sessions, user_id)
    }
}

/// Debug 实现脱敏 URL 中的密码
impl fmt::Debug for RedisConfig {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let redacted_url = redact_redis_url(&self.url);
        f.debug_struct("RedisConfig")
            .field("url", &redacted_url)
            .field("key_prefix_ver", &self.key_prefix_ver)
            .field("key_prefix_bl", &self.key_prefix_bl)
            .field("key_prefix_sessions", &self.key_prefix_sessions)
            .field("connection_timeout", &self.connection_timeout)
            .field("command_timeout", &self.command_timeout)
            .finish()
    }
}

/// 脱敏 Redis URL 中的密码部分
///
/// `redis://:secret@host:port` → `redis://[REDACTED]@host:port`
fn redact_redis_url(url: &str) -> String {
    if let Some(at_pos) = url.find('@') {
        if let Some(scheme_end) = url.find("://") {
            let password_start = scheme_end + 3;
            if at_pos > password_start {
                let (before, after) = url.split_at(at_pos);
                let scheme = &before[..password_start];
                return format!("{}[REDACTED]{}", scheme, after);
            }
        }
    }
    url.to_string()
}

// ── RedisRefreshTokenStore ──

/// Redis 版本号存储
///
/// 实现 [`RefreshTokenStore`] trait,使用 Redis `GET` / `INCR` 命令。
/// key 格式:`{key_prefix_ver}:{user_id}`,不存在时返回 0(与 Memory 行为一致)。
pub struct RedisRefreshTokenStore {
    conn: ConnectionManager,
    config: RedisConfig,
}

impl RedisRefreshTokenStore {
    /// 创建 Redis 版本号存储
    ///
    /// 内部建立 `ConnectionManager`(自动重连 + 连接池复用)。
    pub async fn new(config: RedisConfig) -> Result<Self, RefreshTokenError> {
        let client = redis::Client::open(config.url.as_str())
            .map_err(|e| RefreshTokenError::Cache(format!("redis client open failed: {e}")))?;

        let conn = tokio::time::timeout(config.connection_timeout, client.get_connection_manager())
            .await
            .map_err(|_| RefreshTokenError::ServiceUnavailable)?
            .map_err(|e| RefreshTokenError::Cache(format!("redis connect failed: {e}")))?;

        Ok(Self { conn, config })
    }
}

#[async_trait::async_trait]
impl RefreshTokenStore for RedisRefreshTokenStore {
    async fn get_version(&self, user_id: i64) -> Result<u64, RefreshTokenError> {
        let key = self.config.ver_key(user_id);
        let mut conn = self.conn.clone();
        let result: Option<u64> = tokio::time::timeout(
            self.config.command_timeout,
            conn.get::<&str, Option<u64>>(&key),
        )
        .await
        .map_err(|_| RefreshTokenError::ServiceUnavailable)?
        .map_err(|e| RefreshTokenError::Cache(format!("redis GET failed: {e}")))?;

        Ok(result.unwrap_or(0))
    }

    async fn increment_version(&self, user_id: i64) -> Result<u64, RefreshTokenError> {
        let key = self.config.ver_key(user_id);
        let mut conn = self.conn.clone();
        let new_version: u64 = tokio::time::timeout(
            self.config.command_timeout,
            conn.incr::<&str, u64, u64>(&key, 1),
        )
        .await
        .map_err(|_| RefreshTokenError::ServiceUnavailable)?
        .map_err(|e| RefreshTokenError::Cache(format!("redis INCR failed: {e}")))?;

        Ok(new_version)
    }
}

// ── RedisTokenBlacklist ──

/// Redis Token 黑名单
///
/// 实现 [`TokenBlacklist`] trait,使用 Redis `EXISTS` / `SETEX` 命令。
/// key 格式:`{key_prefix_bl}:{jti}`,TTL 由调用方传入(Token 剩余有效期)。
pub struct RedisTokenBlacklist {
    conn: ConnectionManager,
    config: RedisConfig,
}

impl RedisTokenBlacklist {
    /// 创建 Redis Token 黑名单
    pub async fn new(config: RedisConfig) -> Result<Self, RefreshTokenError> {
        let client = redis::Client::open(config.url.as_str())
            .map_err(|e| RefreshTokenError::Cache(format!("redis client open failed: {e}")))?;

        let conn = tokio::time::timeout(config.connection_timeout, client.get_connection_manager())
            .await
            .map_err(|_| RefreshTokenError::ServiceUnavailable)?
            .map_err(|e| RefreshTokenError::Cache(format!("redis connect failed: {e}")))?;

        Ok(Self { conn, config })
    }
}

#[async_trait::async_trait]
impl TokenBlacklist for RedisTokenBlacklist {
    async fn revoke(&self, jti: &str, ttl_secs: u64) -> Result<(), RefreshTokenError> {
        if ttl_secs == 0 {
            return Ok(());
        }
        let key = self.config.bl_key(jti);
        let mut conn = self.conn.clone();
        tokio::time::timeout(
            self.config.command_timeout,
            conn.set_ex::<&str, &str, ()>(&key, "1", ttl_secs),
        )
        .await
        .map_err(|_| RefreshTokenError::ServiceUnavailable)?
        .map_err(|e| RefreshTokenError::Cache(format!("redis SETEX failed: {e}")))?;

        Ok(())
    }

    async fn is_revoked(&self, jti: &str) -> Result<bool, RefreshTokenError> {
        let key = self.config.bl_key(jti);
        let mut conn = self.conn.clone();
        let exists: bool =
            tokio::time::timeout(self.config.command_timeout, conn.exists::<&str, bool>(&key))
                .await
                .map_err(|_| RefreshTokenError::ServiceUnavailable)?
                .map_err(|e| RefreshTokenError::Cache(format!("redis EXISTS failed: {e}")))?;

        Ok(exists)
    }
}

// ── RedisDeviceSessionStore ──

/// Redis 设备会话存储
///
/// 实现 [`DeviceSessionStore`] trait,使用 Redis Hash 命令。
/// key 格式:`{key_prefix_sessions}:{user_id}`,field 为 `{device_id}`,
/// value 为 `serde_json(DeviceSession)`。
pub struct RedisDeviceSessionStore {
    conn: ConnectionManager,
    config: RedisConfig,
}

impl RedisDeviceSessionStore {
    /// 创建 Redis 设备会话存储
    pub async fn new(config: RedisConfig) -> Result<Self, RefreshTokenError> {
        let client = redis::Client::open(config.url.as_str())
            .map_err(|e| RefreshTokenError::Cache(format!("redis client open failed: {e}")))?;

        let conn = tokio::time::timeout(config.connection_timeout, client.get_connection_manager())
            .await
            .map_err(|_| RefreshTokenError::ServiceUnavailable)?
            .map_err(|e| RefreshTokenError::Cache(format!("redis connect failed: {e}")))?;

        Ok(Self { conn, config })
    }

    /// 从已有 ConnectionManager 创建(共享连接池)
    pub fn from_conn(conn: ConnectionManager, config: RedisConfig) -> Self {
        Self { conn, config }
    }
}

#[async_trait::async_trait]
impl DeviceSessionStore for RedisDeviceSessionStore {
    async fn register_session(
        &self,
        user_id: i64,
        device_id: &str,
        device_info: &DeviceInfo,
        jti: &str,
        access_jti: &str,
    ) -> Result<(), RefreshTokenError> {
        let now = chrono::Utc::now().timestamp();
        let session = DeviceSession {
            device_id: device_id.to_string(),
            device_info: device_info.clone(),
            jti: jti.to_string(),
            access_jti: access_jti.to_string(),
            created_at: now,
            last_active: now,
        };
        let key = self.config.sessions_key(user_id);
        let value = serde_json::to_string(&session)
            .map_err(|e| RefreshTokenError::Cache(format!("json serialize failed: {e}")))?;
        let mut conn = self.conn.clone();
        tokio::time::timeout(
            self.config.command_timeout,
            conn.hset::<&str, &str, &str, ()>(&key, device_id, &value),
        )
        .await
        .map_err(|_| RefreshTokenError::ServiceUnavailable)?
        .map_err(|e| RefreshTokenError::Cache(format!("redis HSET failed: {e}")))?;
        Ok(())
    }

    async fn get_sessions(&self, user_id: i64) -> Result<Vec<DeviceSession>, RefreshTokenError> {
        let key = self.config.sessions_key(user_id);
        let mut conn = self.conn.clone();
        let map: std::collections::HashMap<String, String> = tokio::time::timeout(
            self.config.command_timeout,
            conn.hgetall::<&str, std::collections::HashMap<String, String>>(&key),
        )
        .await
        .map_err(|_| RefreshTokenError::ServiceUnavailable)?
        .map_err(|e| RefreshTokenError::Cache(format!("redis HGETALL failed: {e}")))?;

        let mut sessions = Vec::with_capacity(map.len());
        for (_, v) in map {
            let session: DeviceSession = serde_json::from_str(&v)
                .map_err(|e| RefreshTokenError::Cache(format!("json deserialize failed: {e}")))?;
            sessions.push(session);
        }
        Ok(sessions)
    }

    async fn get_session(
        &self,
        user_id: i64,
        device_id: &str,
    ) -> Result<Option<DeviceSession>, RefreshTokenError> {
        let key = self.config.sessions_key(user_id);
        let mut conn = self.conn.clone();
        let value: Option<String> = tokio::time::timeout(
            self.config.command_timeout,
            conn.hget::<&str, &str, Option<String>>(&key, device_id),
        )
        .await
        .map_err(|_| RefreshTokenError::ServiceUnavailable)?
        .map_err(|e| RefreshTokenError::Cache(format!("redis HGET failed: {e}")))?;

        match value {
            Some(v) => {
                let session: DeviceSession = serde_json::from_str(&v).map_err(|e| {
                    RefreshTokenError::Cache(format!("json deserialize failed: {e}"))
                })?;
                Ok(Some(session))
            }
            None => Ok(None),
        }
    }

    async fn revoke_session(
        &self,
        user_id: i64,
        device_id: &str,
    ) -> Result<Option<(String, String)>, RefreshTokenError> {
        let key = self.config.sessions_key(user_id);
        let mut conn = self.conn.clone();

        let value: Option<String> = tokio::time::timeout(
            self.config.command_timeout,
            conn.hget::<&str, &str, Option<String>>(&key, device_id),
        )
        .await
        .map_err(|_| RefreshTokenError::ServiceUnavailable)?
        .map_err(|e| RefreshTokenError::Cache(format!("redis HGET failed: {e}")))?;

        match value {
            Some(v) => {
                let session: DeviceSession = serde_json::from_str(&v).map_err(|e| {
                    RefreshTokenError::Cache(format!("json deserialize failed: {e}"))
                })?;
                tokio::time::timeout(
                    self.config.command_timeout,
                    conn.hdel::<&str, &str, ()>(&key, device_id),
                )
                .await
                .map_err(|_| RefreshTokenError::ServiceUnavailable)?
                .map_err(|e| RefreshTokenError::Cache(format!("redis HDEL failed: {e}")))?;
                Ok(Some((session.jti, session.access_jti)))
            }
            None => Ok(None),
        }
    }

    async fn update_last_active(
        &self,
        user_id: i64,
        device_id: &str,
    ) -> Result<(), RefreshTokenError> {
        let key = self.config.sessions_key(user_id);
        let mut conn = self.conn.clone();

        let value: Option<String> = tokio::time::timeout(
            self.config.command_timeout,
            conn.hget::<&str, &str, Option<String>>(&key, device_id),
        )
        .await
        .map_err(|_| RefreshTokenError::ServiceUnavailable)?
        .map_err(|e| RefreshTokenError::Cache(format!("redis HGET failed: {e}")))?;

        match value {
            Some(v) => {
                let mut session: DeviceSession = serde_json::from_str(&v).map_err(|e| {
                    RefreshTokenError::Cache(format!("json deserialize failed: {e}"))
                })?;
                session.last_active = chrono::Utc::now().timestamp();
                let new_value = serde_json::to_string(&session)
                    .map_err(|e| RefreshTokenError::Cache(format!("json serialize failed: {e}")))?;
                tokio::time::timeout(
                    self.config.command_timeout,
                    conn.hset::<&str, &str, &str, ()>(&key, device_id, &new_value),
                )
                .await
                .map_err(|_| RefreshTokenError::ServiceUnavailable)?
                .map_err(|e| RefreshTokenError::Cache(format!("redis HSET failed: {e}")))?;
                Ok(())
            }
            None => Ok(()),
        }
    }

    async fn update_session_jti(
        &self,
        user_id: i64,
        device_id: &str,
        new_jti: &str,
    ) -> Result<(), RefreshTokenError> {
        let key = self.config.sessions_key(user_id);
        let mut conn = self.conn.clone();

        let value: Option<String> = tokio::time::timeout(
            self.config.command_timeout,
            conn.hget::<&str, &str, Option<String>>(&key, device_id),
        )
        .await
        .map_err(|_| RefreshTokenError::ServiceUnavailable)?
        .map_err(|e| RefreshTokenError::Cache(format!("redis HGET failed: {e}")))?;

        match value {
            Some(v) => {
                let mut session: DeviceSession = serde_json::from_str(&v).map_err(|e| {
                    RefreshTokenError::Cache(format!("json deserialize failed: {e}"))
                })?;
                session.jti = new_jti.to_string();
                session.last_active = chrono::Utc::now().timestamp();
                let new_value = serde_json::to_string(&session)
                    .map_err(|e| RefreshTokenError::Cache(format!("json serialize failed: {e}")))?;
                tokio::time::timeout(
                    self.config.command_timeout,
                    conn.hset::<&str, &str, &str, ()>(&key, device_id, &new_value),
                )
                .await
                .map_err(|_| RefreshTokenError::ServiceUnavailable)?
                .map_err(|e| RefreshTokenError::Cache(format!("redis HSET failed: {e}")))?;
                Ok(())
            }
            None => Ok(()),
        }
    }

    async fn cleanup_expired(
        &self,
        user_id: i64,
        ttl_secs: i64,
    ) -> Result<Vec<(String, String)>, RefreshTokenError> {
        let key = self.config.sessions_key(user_id);
        let mut conn = self.conn.clone();

        let map: std::collections::HashMap<String, String> = tokio::time::timeout(
            self.config.command_timeout,
            conn.hgetall::<&str, std::collections::HashMap<String, String>>(&key),
        )
        .await
        .map_err(|_| RefreshTokenError::ServiceUnavailable)?
        .map_err(|e| RefreshTokenError::Cache(format!("redis HGETALL failed: {e}")))?;

        let now = chrono::Utc::now().timestamp();
        let mut expired_fields = Vec::new();
        let mut jti_list = Vec::new();

        for (field, v) in map {
            let session: DeviceSession = serde_json::from_str(&v)
                .map_err(|e| RefreshTokenError::Cache(format!("json deserialize failed: {e}")))?;
            if session.last_active + ttl_secs < now {
                jti_list.push((session.jti.clone(), session.access_jti.clone()));
                expired_fields.push(field);
            }
        }

        if !expired_fields.is_empty() {
            for field in &expired_fields {
                tokio::time::timeout(
                    self.config.command_timeout,
                    conn.hdel::<&str, &str, ()>(&key, field),
                )
                .await
                .map_err(|_| RefreshTokenError::ServiceUnavailable)?
                .map_err(|e| RefreshTokenError::Cache(format!("redis HDEL failed: {e}")))?;
            }
            tracing::debug!(
                user_id,
                count = expired_fields.len(),
                "expired sessions cleaned"
            );
        }

        Ok(jti_list)
    }

    async fn clear_user_sessions(
        &self,
        user_id: i64,
    ) -> Result<Vec<(String, String)>, RefreshTokenError> {
        let key = self.config.sessions_key(user_id);
        let mut conn = self.conn.clone();

        let map: std::collections::HashMap<String, String> = tokio::time::timeout(
            self.config.command_timeout,
            conn.hgetall::<&str, std::collections::HashMap<String, String>>(&key),
        )
        .await
        .map_err(|_| RefreshTokenError::ServiceUnavailable)?
        .map_err(|e| RefreshTokenError::Cache(format!("redis HGETALL failed: {e}")))?;

        let mut jti_list = Vec::with_capacity(map.len());
        for (_, v) in map {
            let session: DeviceSession = serde_json::from_str(&v)
                .map_err(|e| RefreshTokenError::Cache(format!("json deserialize failed: {e}")))?;
            jti_list.push((session.jti, session.access_jti));
        }

        tokio::time::timeout(self.config.command_timeout, conn.del::<&str, ()>(&key))
            .await
            .map_err(|_| RefreshTokenError::ServiceUnavailable)?
            .map_err(|e| RefreshTokenError::Cache(format!("redis DEL failed: {e}")))?;

        Ok(jti_list)
    }
}

// ── 便捷工厂 ──

/// 一次创建 Redis Store + Blacklist,共享同一 ConnectionManager
///
/// 对齐 design.md §2.5。返回 `(Store, Blacklist)`,两者各自持有独立的
/// `ConnectionManager` clone(内部 Arc 共享连接池)。
pub async fn create_redis_stores(
    config: RedisConfig,
) -> Result<
    (
        std::sync::Arc<dyn RefreshTokenStore>,
        std::sync::Arc<dyn TokenBlacklist>,
    ),
    RefreshTokenError,
> {
    let store = RedisRefreshTokenStore::new(config.clone()).await?;
    let blacklist = RedisTokenBlacklist::new(config).await?;
    Ok((std::sync::Arc::new(store), std::sync::Arc::new(blacklist)))
}

/// 一次创建 Redis Store + Blacklist + DeviceSessionStore,共享同一 ConnectionManager
///
/// 对齐 multi-device-session design.md §6.3。返回三元组,
/// 三者各自持有独立的 `ConnectionManager` clone(内部 Arc 共享连接池)。
pub async fn create_redis_stores_with_devices(
    config: RedisConfig,
) -> Result<
    (
        std::sync::Arc<dyn RefreshTokenStore>,
        std::sync::Arc<dyn TokenBlacklist>,
        std::sync::Arc<dyn DeviceSessionStore>,
    ),
    RefreshTokenError,
> {
    let store = RedisRefreshTokenStore::new(config.clone()).await?;
    let blacklist = RedisTokenBlacklist::new(config.clone()).await?;
    let device_store = RedisDeviceSessionStore::new(config).await?;
    Ok((
        std::sync::Arc::new(store),
        std::sync::Arc::new(blacklist),
        std::sync::Arc::new(device_store),
    ))
}

// ── 单元测试 ──

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_redis_config_default() {
        let config = RedisConfig::default();
        assert_eq!(config.url, "redis://127.0.0.1:6379");
        assert_eq!(config.key_prefix_ver, "sso:ver");
        assert_eq!(config.key_prefix_bl, "sso:bl");
        assert_eq!(config.connection_timeout, Duration::from_secs(3));
        assert_eq!(config.command_timeout, Duration::from_secs(2));
    }

    #[test]
    fn test_redis_config_from_url() {
        let config = RedisConfig::from_url("redis://localhost:6380/1");
        assert_eq!(config.url, "redis://localhost:6380/1");
        assert_eq!(config.key_prefix_ver, "sso:ver");
    }

    #[test]
    fn test_redis_config_debug_redacts_password() {
        let config = RedisConfig::from_url("redis://:secret_pass@127.0.0.1:6379");
        let debug_str = format!("{:?}", config);
        assert!(debug_str.contains("[REDACTED]"));
        assert!(!debug_str.contains("secret_pass"));
    }

    #[test]
    fn test_redis_config_debug_no_password() {
        let config = RedisConfig::from_url("redis://127.0.0.1:6379");
        let debug_str = format!("{:?}", config);
        assert!(!debug_str.contains("[REDACTED]"));
        assert!(debug_str.contains("127.0.0.1:6379"));
    }

    #[test]
    fn test_ver_key_format() {
        let config = RedisConfig::default();
        assert_eq!(config.ver_key(1), "sso:ver:1");
        assert_eq!(config.ver_key(42), "sso:ver:42");
    }

    #[test]
    fn test_bl_key_format() {
        let config = RedisConfig::default();
        assert_eq!(config.bl_key("abc123"), "sso:bl:abc123");
    }

    #[test]
    fn test_redact_redis_url_with_password() {
        let redacted = redact_redis_url("redis://:mypassword@host:6379/0");
        assert!(redacted.contains("[REDACTED]"));
        assert!(!redacted.contains("mypassword"));
        assert!(redacted.contains("host:6379"));
    }

    #[test]
    fn test_redact_redis_url_without_password() {
        let redacted = redact_redis_url("redis://127.0.0.1:6379");
        assert_eq!(redacted, "redis://127.0.0.1:6379");
    }

    #[test]
    fn test_redact_redis_url_with_user_and_password() {
        let redacted = redact_redis_url("redis://user:pass@host:6379");
        assert!(redacted.contains("[REDACTED]"));
        assert!(!redacted.contains("pass"));
    }
}