auth-framework 0.6.0-rc150

A comprehensive, production-ready authentication and authorization framework for Rust applications
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
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
//! Redis storage backend for auth-framework.
//!
//! This module provides a production-ready Redis storage implementation
//! with connection pooling, serialization, and error handling.

use crate::errors::StorageError;
use crate::{
    errors::{AuthError, Result},
    storage::{AuthStorage, SessionData},
    tokens::AuthToken,
};
use async_trait::async_trait;
use redis::aio::MultiplexedConnection;
use redis::{AsyncCommands, Client};
use serde_json;
use std::time::Duration;

/// Redis storage backend for authentication data
#[derive(Clone)]
pub struct RedisStorage {
    client: Client,
    key_prefix: String,
    default_ttl: Duration,
}

impl RedisStorage {
    /// Create a new Redis storage backend
    pub async fn new(redis_url: &str) -> Result<Self> {
        let client = Client::open(redis_url)
            .map_err(|e| AuthError::Storage(StorageError::connection_failed(e.to_string())))?;
        Ok(Self {
            client,
            key_prefix: "auth:".to_string(),
            default_ttl: Duration::from_secs(3600), // 1 hour
        })
    }

    /// Create Redis storage with custom configuration
    pub async fn with_config(
        redis_url: &str,
        key_prefix: impl Into<String>,
        default_ttl: Duration,
    ) -> Result<Self> {
        let mut storage = Self::new(redis_url).await?;
        storage.key_prefix = key_prefix.into();
        storage.default_ttl = default_ttl;
        Ok(storage)
    }

    fn token_key(&self, token_id: &str) -> String {
        format!("{}token:{}", self.key_prefix, token_id)
    }

    /// The raw access token is a bearer credential and is never used as a
    /// key name (see [`crate::storage::key_names`]).
    fn access_token_key(&self, access_token: &str) -> String {
        format!(
            "{}access_h:{}",
            self.key_prefix,
            crate::storage::key_names::digest("access_token", access_token)
        )
    }

    /// The pre-fix name, kept only to read-and-migrate or delete old rows.
    fn legacy_access_token_key(&self, access_token: &str) -> String {
        format!("{}access:{}", self.key_prefix, access_token)
    }

    fn user_tokens_key(&self, user_id: &str) -> String {
        format!("{}user:{}:tokens", self.key_prefix, user_id)
    }

    /// The session id is a bearer credential; it is never used as a key name.
    fn session_key(&self, session_id: &str) -> String {
        format!(
            "{}session_h:{}",
            self.key_prefix,
            crate::storage::key_names::digest("session", session_id)
        )
    }

    /// The pre-fix name, kept only to read-and-migrate or delete old rows.
    fn legacy_session_key(&self, session_id: &str) -> String {
        format!("{}session:{}", self.key_prefix, session_id)
    }

    /// Every session key, under the digest name and under the legacy name,
    /// found with cursor-based SCAN (SEC-M3). Two exact-prefix patterns, so
    /// nothing else sharing the key prefix matches. A session present under both
    /// names (a crash between the two writes of a store) appears twice.
    async fn session_keys(
        &self,
        conn: &mut redis::aio::MultiplexedConnection,
    ) -> Result<Vec<String>> {
        let mut all = Vec::new();
        for pattern in [
            format!("{}session_h:*", self.key_prefix),
            format!("{}session:*", self.key_prefix),
        ] {
            let mut cursor: u64 = 0;
            loop {
                let (next_cursor, keys): (u64, Vec<String>) = redis::cmd("SCAN")
                    .arg(cursor)
                    .arg("MATCH")
                    .arg(&pattern)
                    .arg("COUNT")
                    .arg(100)
                    .query_async(&mut *conn)
                    .await
                    .map_err(|e| {
                        AuthError::Storage(StorageError::operation_failed(e.to_string()))
                    })?;
                all.extend(keys);
                cursor = next_cursor;
                if cursor == 0 {
                    break;
                }
            }
        }
        Ok(all)
    }

    /// Read `new_key`; on a miss, move a row stored under `legacy_key` (the raw
    /// credential name used before digest naming) to `new_key`, keeping its
    /// remaining lifetime, and return it.
    async fn get_migrating(&self, new_key: &str, legacy_key: &str) -> Result<Option<String>> {
        let mut conn = self.get_connection().await?;
        // Plain read first: it needs no scripting permission, and a digest-named
        // row is the common case.
        let value: Option<String> = redis::cmd("GET")
            .arg(new_key)
            .query_async(&mut conn)
            .await
            .map_err(|e| AuthError::Storage(StorageError::operation_failed(e.to_string())))?;
        if value.is_some() {
            // A legacy twin can only be left by an interrupted write and still
            // holds the raw id in its name: drop it (best effort).
            let _ = redis::cmd("DEL")
                .arg(legacy_key)
                .query_async::<usize>(&mut conn)
                .await;
            return Ok(value);
        }
        // One Lua script, so a concurrent store or delete cannot interleave with the
        // move: it never overwrites a row already at `new_key` and never recreates
        // a row that was deleted.
        const MIGRATE: &str = r#"
            local l = redis.call('GET', KEYS[2])
            if not l then return redis.call('GET', KEYS[1]) end
            local v = redis.call('GET', KEYS[1])
            if v then
                redis.call('DEL', KEYS[2])
                return v
            end
            local t = redis.call('PTTL', KEYS[2])
            if t > 0 then
                redis.call('SET', KEYS[1], l, 'PX', t)
            elseif t == -1 then
                redis.call('SET', KEYS[1], l)
            else
                return false
            end
            redis.call('DEL', KEYS[2])
            return l
        "#;
        match redis::Script::new(MIGRATE)
            .key(new_key)
            .key(legacy_key)
            .invoke_async::<Option<String>>(&mut conn)
            .await
        {
            Ok(value) => Ok(value),
            Err(script_err) => {
                // Scripting denied (restricted ACL) or unavailable: serve the row
                // where it is. It moves once scripts are allowed or the record is
                // rewritten.
                tracing::warn!(
                    error = %script_err,
                    "legacy-name migration script failed; serving the row unmigrated"
                );
                let legacy: Option<String> = redis::cmd("GET")
                    .arg(legacy_key)
                    .query_async(&mut conn)
                    .await
                    .map_err(|e| {
                        AuthError::Storage(StorageError::operation_failed(e.to_string()))
                    })?;
                Ok(legacy)
            }
        }
    }

    /// Delete a key left under a pre-fix (raw credential) name, if any.
    async fn del_legacy(&self, legacy_key: &str) -> Result<()> {
        let mut conn = self.get_connection().await?;
        let _: usize = conn
            .del(legacy_key)
            .await
            .map_err(|e| AuthError::Storage(StorageError::operation_failed(e.to_string())))?;
        Ok(())
    }

    fn kv_key(&self, key: &str) -> String {
        format!("{}kv:{}", self.key_prefix, key)
    }

    /// Verify connectivity to the Redis server by sending a PING command.
    ///
    /// Returns `Ok(())` on success or an `AuthError::Storage` on failure.
    pub async fn health_check(&self) -> Result<()> {
        let mut conn = self.get_connection().await?;
        let pong: String = redis::cmd("PING")
            .query_async(&mut conn)
            .await
            .map_err(|e| AuthError::Storage(StorageError::connection_failed(e.to_string())))?;
        if pong == "PONG" {
            Ok(())
        } else {
            Err(AuthError::Storage(StorageError::connection_failed(
                format!("unexpected PING response: {pong}"),
            )))
        }
    }

    async fn get_connection(&self) -> Result<MultiplexedConnection> {
        self.client
            .get_multiplexed_async_connection()
            .await
            .map_err(|e| AuthError::Storage(StorageError::connection_failed(e.to_string())))
    }
}

/// Removes the live keys among `KEYS[1..n-1]` and sets `KEYS[n]` to `ARGV[1]` (expiring after
/// `ARGV[2]` ms when that is above zero), but only if one of them was live and `KEYS[n]` is
/// absent. A script runs atomically on the server. Returns 1 when it swapped, 0 otherwise.
pub(crate) const SWAP_KV_SCRIPT: &str = r#"
local last = #KEYS
local live = false
for i = 1, last - 1 do
  if redis.call('EXISTS', KEYS[i]) == 1 then live = true end
end
if not live then return 0 end
if redis.call('EXISTS', KEYS[last]) == 1 then return 0 end
for i = 1, last - 1 do redis.call('DEL', KEYS[i]) end
local ttl = tonumber(ARGV[2])
if ttl > 0 then
  redis.call('SET', KEYS[last], ARGV[1], 'PX', ttl)
else
  redis.call('SET', KEYS[last], ARGV[1])
end
return 1
"#;

#[async_trait]
impl AuthStorage for RedisStorage {
    async fn update_token(&self, token: &AuthToken) -> Result<()> {
        // For Redis, update is just an overwrite
        self.store_token(token).await
    }

    async fn store_session(&self, session_id: &str, data: &SessionData) -> Result<()> {
        let mut conn = self.get_connection().await?;
        let session_key = self.session_key(session_id);
        let session_data = serde_json::to_string(data)
            .map_err(|e| AuthError::Storage(StorageError::serialization(e.to_string())))?;
        let ttl = if data.expires_at > chrono::Utc::now() {
            (data.expires_at - chrono::Utc::now()).num_seconds() as u64
        } else {
            self.default_ttl.as_secs()
        };
        let _: () = conn
            .set_ex(&session_key, &session_data, ttl)
            .await
            .map_err(|e| AuthError::Storage(StorageError::operation_failed(e.to_string())))?;
        // Drop a record left under the pre-fix name (it held the raw session id).
        self.del_legacy(&self.legacy_session_key(session_id))
            .await?;
        Ok(())
    }

    async fn get_session(&self, session_id: &str) -> Result<Option<SessionData>> {
        let session_data = self
            .get_migrating(
                &self.session_key(session_id),
                &self.legacy_session_key(session_id),
            )
            .await?;
        match session_data {
            Some(data) => {
                let session: SessionData = serde_json::from_str(&data)
                    .map_err(|e| AuthError::Storage(StorageError::serialization(e.to_string())))?;
                Ok(Some(session))
            }
            None => Ok(None),
        }
    }

    async fn delete_session(&self, session_id: &str) -> Result<()> {
        let mut conn = self.get_connection().await?;
        let session_key = self.session_key(session_id);
        // Legacy name first: a migration that runs in between then finds no
        // legacy row to move, so a deleted session cannot be recreated.
        self.del_legacy(&self.legacy_session_key(session_id))
            .await?;
        let _: usize = conn
            .del(&session_key)
            .await
            .map_err(|e| AuthError::Storage(StorageError::operation_failed(e.to_string())))?;
        Ok(())
    }

    async fn list_user_sessions(&self, user_id: &str) -> Result<Vec<SessionData>> {
        let mut conn = self.get_connection().await?;
        let keys = self.session_keys(&mut conn).await?;

        let mut user_sessions = Vec::new();
        let mut seen = std::collections::HashSet::new();
        let legacy_prefix = self.legacy_session_key("");
        for key in keys {
            // A row still under the pre-fix name is moved to its digest name as
            // it is listed, so it stops exposing the raw session id in key names.
            let session_json = match key.strip_prefix(&legacy_prefix) {
                Some(session_id) => self
                    .get_migrating(&self.session_key(session_id), &key)
                    .await
                    .ok()
                    .flatten(),
                None => conn.get::<_, String>(&key).await.ok(),
            };
            if let Some(session_json) = session_json
                && let Ok(session) = serde_json::from_str::<SessionData>(&session_json)
                && session.user_id == user_id
                && !session.is_expired()
                && seen.insert(session.session_id.clone())
            {
                user_sessions.push(session);
            }
        }

        Ok(user_sessions)
    }

    async fn store_kv_if_absent(
        &self,
        key: &str,
        value: &[u8],
        ttl: Option<Duration>,
    ) -> Result<bool> {
        let mut conn = self.get_connection().await?;
        let kv_key = self.kv_key(key);
        // SET ... NX [PX ms]: atomic; the reply is OK when set and nil when the key exists.
        let mut cmd = redis::cmd("SET");
        cmd.arg(&kv_key).arg(value).arg("NX");
        if let Some(duration) = ttl {
            let millis = u64::try_from(duration.as_millis())
                .unwrap_or(u64::MAX)
                .max(1);
            cmd.arg("PX").arg(millis);
        }
        let reply: Option<String> = cmd
            .query_async(&mut conn)
            .await
            .map_err(|e| AuthError::Storage(StorageError::operation_failed(e.to_string())))?;
        Ok(reply.is_some())
    }

    async fn swap_kv(
        &self,
        remove: &[String],
        key: &str,
        value: &[u8],
        ttl: Option<Duration>,
    ) -> Result<bool> {
        if remove.is_empty() {
            return Ok(false);
        }
        let mut conn = self.get_connection().await?;
        let script = redis::Script::new(SWAP_KV_SCRIPT);
        let mut invocation = script.prepare_invoke();
        for name in remove {
            invocation.key(self.kv_key(name));
        }
        invocation.key(self.kv_key(key));
        let millis = ttl.map_or(0, |d| {
            u64::try_from(d.as_millis()).unwrap_or(u64::MAX).max(1)
        });
        let swapped: i64 = invocation
            .arg(value)
            .arg(millis)
            .invoke_async(&mut conn)
            .await
            .map_err(|e| AuthError::Storage(StorageError::operation_failed(e.to_string())))?;
        Ok(swapped == 1)
    }

    fn supports_atomic_swap(&self) -> bool {
        true
    }

    async fn store_kv(&self, key: &str, value: &[u8], ttl: Option<Duration>) -> Result<()> {
        let mut conn = self.get_connection().await?;
        let kv_key = self.kv_key(key);
        // SEC-L5: When no TTL is specified, store without expiration so that
        // configuration data and permanent records don't silently vanish.
        if let Some(duration) = ttl {
            // PSETEX, not SETEX: a remaining TTL under one second must not
            // become `SETEX key 0 ...`, which Redis rejects.
            let millis = u64::try_from(duration.as_millis())
                .unwrap_or(u64::MAX)
                .max(1);
            let _: () = redis::cmd("PSETEX")
                .arg(&kv_key)
                .arg(millis)
                .arg(value)
                .query_async(&mut conn)
                .await
                .map_err(|e| AuthError::Storage(StorageError::operation_failed(e.to_string())))?;
        } else {
            let _: () = conn
                .set(&kv_key, value)
                .await
                .map_err(|e| AuthError::Storage(StorageError::operation_failed(e.to_string())))?;
        }
        Ok(())
    }

    async fn get_kv(&self, key: &str) -> Result<Option<Vec<u8>>> {
        let mut conn = self.get_connection().await?;
        let kv_key = self.kv_key(key);
        let value: Option<Vec<u8>> = conn
            .get(&kv_key)
            .await
            .map_err(|e| AuthError::Storage(StorageError::operation_failed(e.to_string())))?;
        Ok(value)
    }

    async fn get_kv_ttl(&self, key: &str) -> Result<Option<Duration>> {
        let mut conn = self.get_connection().await?;
        let kv_key = self.kv_key(key);
        // PTTL: -2 = no such key, -1 = no expiry, otherwise milliseconds left.
        let millis: i64 = conn
            .pttl(&kv_key)
            .await
            .map_err(|e| AuthError::Storage(StorageError::operation_failed(e.to_string())))?;
        Ok(u64::try_from(millis)
            .ok()
            .filter(|millis| *millis > 0)
            .map(Duration::from_millis))
    }

    fn tracks_kv_ttl(&self) -> bool {
        true
    }

    async fn delete_kv(&self, key: &str) -> Result<()> {
        let mut conn = self.get_connection().await?;
        let kv_key = self.kv_key(key);
        let _: usize = conn
            .del(&kv_key)
            .await
            .map_err(|e| AuthError::Storage(StorageError::operation_failed(e.to_string())))?;
        Ok(())
    }

    async fn list_kv_keys(&self, prefix: &str) -> Result<Vec<String>> {
        let mut conn = self.get_connection().await?;
        let kv_prefix = self.kv_key("");
        // Redis MATCH is a glob: escape its metacharacters in the caller's prefix.
        let mut pattern = String::with_capacity(kv_prefix.len() + prefix.len() + 1);
        for c in kv_prefix.chars().chain(prefix.chars()) {
            if matches!(c, '*' | '?' | '[' | ']' | '\\') {
                pattern.push('\\');
            }
            pattern.push(c);
        }
        pattern.push('*');

        let mut keys = Vec::new();
        let mut cursor: u64 = 0;
        loop {
            let (next, batch): (u64, Vec<String>) = redis::cmd("SCAN")
                .arg(cursor)
                .arg("MATCH")
                .arg(&pattern)
                .arg("COUNT")
                .arg(100)
                .query_async(&mut conn)
                .await
                .map_err(|e| AuthError::Storage(StorageError::operation_failed(e.to_string())))?;
            keys.extend(
                batch
                    .into_iter()
                    .filter_map(|k| k.strip_prefix(&kv_prefix).map(str::to_owned)),
            );
            cursor = next;
            if cursor == 0 {
                break;
            }
        }
        // SCAN may return a key more than once.
        keys.sort_unstable();
        keys.dedup();
        Ok(keys)
    }

    async fn cleanup_expired(&self) -> Result<()> {
        // Redis handles expiration automatically via TTL
        Ok(())
    }
    async fn store_token(&self, token: &AuthToken) -> Result<()> {
        let mut conn = self.get_connection().await?;

        // Reject already-expired tokens rather than re-activating them with a
        // fresh TTL (SEC-H1).
        let now = chrono::Utc::now();
        if token.expires_at <= now {
            return Err(AuthError::Storage(StorageError::operation_failed(
                "Cannot store an already-expired token".to_string(),
            )));
        }
        let ttl = (token.expires_at - now).num_seconds() as u64;

        // Serialize token
        let token_data = serde_json::to_string(token)
            .map_err(|e| AuthError::Storage(StorageError::serialization(e.to_string())))?;

        // Store token by ID
        let token_key = self.token_key(&token.token_id);
        let _: () = conn
            .set_ex(&token_key, &token_data, ttl)
            .await
            .map_err(|e| AuthError::Storage(StorageError::operation_failed(e.to_string())))?;

        // Store access token lookup
        let access_key = self.access_token_key(&token.access_token);
        let _: () = conn
            .set_ex(&access_key, &token.token_id, ttl)
            .await
            .map_err(|e| AuthError::Storage(StorageError::operation_failed(e.to_string())))?;

        // Drop a mapping left under the pre-fix name (it held the raw token).
        self.del_legacy(&self.legacy_access_token_key(&token.access_token))
            .await?;

        // Add to user's token set
        let user_tokens_key = self.user_tokens_key(&token.user_id);
        let _: () = conn
            .sadd(&user_tokens_key, &token.token_id)
            .await
            .map_err(|e| AuthError::Storage(StorageError::operation_failed(e.to_string())))?;

        // Set expiration on user tokens set
        let _: bool = conn
            .expire(&user_tokens_key, ttl as i64)
            .await
            .map_err(|e| AuthError::Storage(StorageError::operation_failed(e.to_string())))?;

        Ok(())
    }

    async fn get_token(&self, token_id: &str) -> Result<Option<AuthToken>> {
        let mut conn = self.get_connection().await?;
        let token_key = self.token_key(token_id);

        let token_data: Option<String> = conn
            .get(&token_key)
            .await
            .map_err(|e| AuthError::Storage(StorageError::operation_failed(e.to_string())))?;

        match token_data {
            Some(data) => {
                let token: AuthToken = serde_json::from_str(&data)
                    .map_err(|e| AuthError::Storage(StorageError::serialization(e.to_string())))?;
                Ok(Some(token))
            }
            None => Ok(None),
        }
    }

    async fn get_token_by_access_token(&self, access_token: &str) -> Result<Option<AuthToken>> {
        let token_id = self
            .get_migrating(
                &self.access_token_key(access_token),
                &self.legacy_access_token_key(access_token),
            )
            .await?;

        match token_id {
            Some(id) => self.get_token(&id).await,
            None => Ok(None),
        }
    }

    async fn delete_token(&self, token_id: &str) -> Result<()> {
        let mut conn = self.get_connection().await?;

        // Get token to find access token and user ID
        if let Some(token) = self.get_token(token_id).await? {
            let token_key = self.token_key(token_id);
            let access_key = self.access_token_key(&token.access_token);
            let user_tokens_key = self.user_tokens_key(&token.user_id);
            self.del_legacy(&self.legacy_access_token_key(&token.access_token))
                .await?;

            // Delete token
            let _: usize = conn
                .del(&token_key)
                .await
                .map_err(|e| AuthError::Storage(StorageError::operation_failed(e.to_string())))?;

            // Delete access token lookup
            let _: usize = conn
                .del(&access_key)
                .await
                .map_err(|e| AuthError::Storage(StorageError::operation_failed(e.to_string())))?;

            // Remove from user's token set
            let _: usize = conn
                .srem(&user_tokens_key, token_id)
                .await
                .map_err(|e| AuthError::Storage(StorageError::operation_failed(e.to_string())))?;
        }
        Ok(())
    }

    async fn list_user_tokens(&self, user_id: &str) -> Result<Vec<AuthToken>> {
        let mut conn = self.get_connection().await?;
        let user_tokens_key = self.user_tokens_key(user_id);

        let token_ids: Vec<String> = conn
            .smembers(&user_tokens_key)
            .await
            .map_err(|e| AuthError::Storage(StorageError::operation_failed(e.to_string())))?;

        let mut tokens = Vec::new();
        for token_id in token_ids {
            if let Some(token) = self.get_token(&token_id).await? {
                tokens.push(token);
            }
        }

        Ok(tokens)
    }

    async fn count_active_sessions(&self) -> Result<u64> {
        let mut conn = self.get_connection().await?;
        let keys = self.session_keys(&mut conn).await?;
        // A session present under both names is one session.
        let keys = crate::storage::key_names::without_shadowed_legacy(
            keys,
            &self.legacy_session_key(""),
            &format!("{}session_h:", self.key_prefix),
            "session",
        );

        let mut active_count = 0u64;
        for key in keys {
            let ttl: i64 = conn
                .ttl(&key)
                .await
                .map_err(|e| AuthError::Storage(StorageError::operation_failed(e.to_string())))?;

            // TTL > 0 means key has expiration and is still active
            // TTL = -1 means key has no expiration (active)
            // TTL = -2 means key doesn't exist (expired)
            if ttl > 0 || ttl == -1 {
                active_count += 1;
            }
        }

        Ok(active_count)
    }
}