Skip to main content

session_guard/store/
valkey.rs

1//! Valkey / Redis store.
2
3use std::{fmt, net::IpAddr, sync::LazyLock};
4
5use redis::{
6    RedisFuture, Script, Value,
7    aio::{ConnectionLike, ConnectionManager},
8    cluster_async::ClusterConnection,
9};
10use serde::Serialize;
11use sha2::{Digest, Sha256};
12use time::OffsetDateTime;
13use uuid::Uuid;
14
15use super::{
16    ClaimScope, SessionRecord, SessionStore, SessionUpdate, Supersede, TokenLookup, TokenRecord, session_bucket,
17    token_bucket,
18};
19use crate::{
20    checks::Check,
21    error::StoreError,
22    event::{ClientSummary, EventKind, SessionEvent, SessionOrigin},
23    fingerprint::Baseline,
24    token::TokenHash,
25};
26
27/// How many sessions one `delete_expired` script invocation removes at most.
28const PURGE_BATCH: usize = 500;
29
30/// How many session ids one `SREM` removes at most.
31const SREM_BATCH: usize = 1000;
32
33/// Lua helpers shared by several scripts. `P` is always a bucket prefix (`prefix{bb}:`), so every
34/// key a script builds shares the hash slot of the keys it was called with.
35macro_rules! lua_helpers {
36    () => {
37        r"
38local function read_session(P, sid)
39  local v = redis.call('HMGET', P .. 's:' .. sid,
40    'subject', 'created', 'auth', 'seen', 'expires', 'step_up', 'baseline', 'origin')
41  if not v[1] then return nil end
42  return {sid, v[1], v[2], v[3], v[4], v[5], v[6], v[7], v[8] or ''}
43end
44
45-- Deletes a session and its tokens; returns its subject, or false if it did not exist.
46local function del_session(P, sid)
47  local s = P .. 's:' .. sid
48  local k = P .. 'k:' .. sid
49  local subject = redis.call('HGET', s, 'subject')
50  for _, hex in ipairs(redis.call('ZRANGE', k, 0, -1)) do
51    redis.call('DEL', P .. 't:' .. hex)
52  end
53  redis.call('DEL', k)
54  redis.call('ZREM', P .. 'x', sid)
55  redis.call('ZREM', P .. 'i', sid)
56  if subject then
57    redis.call('DEL', s)
58    return subject
59  end
60  return false
61end
62"
63    };
64}
65
66/// KEYS: session, token, token set, expiry index. ARGV: bucket prefix, sid, token hex, subject,
67/// created, auth, seen, expires, `step_up`, baseline, `exp_ms`, origin or `''`.
68static INSERT: LazyLock<Script> = LazyLock::new(|| {
69    Script::new(
70        r"
71local P = ARGV[1]
72if redis.call('EXISTS', KEYS[1]) == 1 or redis.call('EXISTS', KEYS[2]) == 1 then return 0 end
73redis.call('HSET', KEYS[1], 'subject', ARGV[4], 'created', ARGV[5], 'auth', ARGV[6],
74  'seen', ARGV[7], 'expires', ARGV[8], 'step_up', ARGV[9], 'baseline', ARGV[10],
75  'exp_ms', ARGV[11], 'cur', ARGV[3], 'seq', 1)
76if ARGV[12] ~= '' then redis.call('HSET', KEYS[1], 'origin', ARGV[12]) end
77redis.call('HSET', KEYS[2], 'sid', ARGV[2], 'seq', 1, 'issued', ARGV[5])
78redis.call('ZADD', KEYS[3], 1, ARGV[3])
79redis.call('ZADD', KEYS[4], ARGV[8], ARGV[2])
80redis.call('ZADD', P .. 'i', ARGV[7], ARGV[2])
81redis.call('PEXPIREAT', KEYS[1], ARGV[11])
82redis.call('PEXPIREAT', KEYS[2], ARGV[11])
83redis.call('PEXPIREAT', KEYS[3], ARGV[11])
84return 1
85",
86    )
87});
88
89/// KEYS: subject set. ARGV: sid, `exp_ms`. Adds a session to the set and keeps the set alive
90/// until the latest member expires.
91static INDEX_ADD: LazyLock<Script> = LazyLock::new(|| {
92    Script::new(
93        r"
94redis.call('SADD', KEYS[1], ARGV[1])
95local pt = redis.call('PEXPIRETIME', KEYS[1])
96if pt == -1 or pt < tonumber(ARGV[2]) then redis.call('PEXPIREAT', KEYS[1], ARGV[2]) end
97return 1
98",
99    )
100});
101
102/// KEYS: subject set, revoking set. Moves every member of the subject set into the revoking set
103/// (keeping the later expiry) and returns the revoking set's members, which includes any a
104/// crashed revoke left behind.
105static INDEX_MOVE: LazyLock<Script> = LazyLock::new(|| {
106    Script::new(
107        r"
108local pt = redis.call('PEXPIRETIME', KEYS[1])
109if pt ~= -2 then
110  local cur = redis.call('PEXPIRETIME', KEYS[2])
111  redis.call('SUNIONSTORE', KEYS[2], KEYS[2], KEYS[1])
112  local at = math.max(pt, cur)
113  if at > 0 then redis.call('PEXPIREAT', KEYS[2], at) end
114  redis.call('DEL', KEYS[1])
115end
116return redis.call('SMEMBERS', KEYS[2])
117",
118    )
119});
120
121/// KEYS: token. ARGV: bucket prefix. Returns hex, issued, used and superseded (or `''`) of
122/// every used token issued after it in its session, oldest first.
123static NEWER_USED: LazyLock<Script> = LazyLock::new(|| {
124    Script::new(
125        r"
126local P = ARGV[1]
127local t = redis.call('HMGET', KEYS[1], 'sid', 'seq')
128if not t[1] then return {} end
129local out = {}
130for _, hex in ipairs(redis.call('ZRANGEBYSCORE', P .. 'k:' .. t[1], '(' .. t[2], '+inf')) do
131  local n = redis.call('HMGET', P .. 't:' .. hex, 'issued', 'used', 'sup')
132  if n[2] then
133    out[#out + 1] = hex
134    out[#out + 1] = n[1]
135    out[#out + 1] = n[2]
136    out[#out + 1] = n[3] or ''
137  end
138end
139return out
140",
141    )
142});
143
144/// KEYS: token. ARGV: bucket prefix.
145static FIND: LazyLock<Script> = LazyLock::new(|| {
146    Script::new(concat!(
147        lua_helpers!(),
148        r"
149local P = ARGV[1]
150local t = redis.call('HMGET', KEYS[1], 'sid', 'seq', 'issued', 'used', 'sup')
151if not t[1] then return false end
152local rec = read_session(P, t[1])
153if not rec then return false end
154local newer = 0
155for _, hex in ipairs(redis.call('ZRANGEBYSCORE', P .. 'k:' .. t[1], '(' .. t[2], '+inf')) do
156  if redis.call('HEXISTS', P .. 't:' .. hex, 'used') == 1 then
157    newer = 1
158    break
159  end
160end
161rec[10] = t[3]
162rec[11] = t[4] or ''
163rec[12] = t[5] or ''
164rec[13] = tostring(newer)
165return rec
166",
167    ))
168});
169
170/// KEYS: session. ARGV: bucket prefix, sid.
171static READ: LazyLock<Script> = LazyLock::new(|| {
172    Script::new(concat!(
173        lua_helpers!(),
174        "return read_session(ARGV[1], ARGV[2]) or false\n"
175    ))
176});
177
178/// KEYS: session. ARGV: bucket prefix, sid, now, supersede mode (`''` for no rotation), mode argument, new token hex,
179/// prune cutoff, `mark_used` hex or `''`, baseline or `''`, `step_up` or `''`, auth or `''`.
180static APPLY: LazyLock<Script> = LazyLock::new(|| {
181    Script::new(
182        r"
183local s = KEYS[1]
184if redis.call('EXISTS', s) == 0 then return 0 end
185local P, sid, now, mode = ARGV[1], ARGV[2], ARGV[3], ARGV[4]
186local rotated = 0
187if mode ~= '' then
188  local cur = redis.call('HGET', s, 'cur')
189  if cur then
190    local ck = P .. 't:' .. cur
191    local holds = false
192    if mode == 'exact' then
193      holds = cur == ARGV[5]
194    elseif mode == 'before' then
195      local issued = tonumber(redis.call('HGET', ck, 'issued'))
196      holds = issued ~= nil and issued < tonumber(ARGV[5])
197    elseif mode == 'current' then
198      holds = redis.call('EXISTS', ck) == 1
199    end
200    local nk = P .. 't:' .. ARGV[6]
201    if holds and redis.call('EXISTS', nk) == 0 then
202      local k = P .. 'k:' .. sid
203      redis.call('HSET', ck, 'sup', now)
204      local seq = redis.call('HINCRBY', s, 'seq', 1)
205      redis.call('HSET', nk, 'sid', sid, 'seq', seq, 'issued', now)
206      local exp = redis.call('HGET', s, 'exp_ms')
207      if exp then redis.call('PEXPIREAT', nk, exp) end
208      redis.call('ZADD', k, seq, ARGV[6])
209      redis.call('HSET', s, 'cur', ARGV[6])
210      local cutoff = tonumber(ARGV[7])
211      for _, hex in ipairs(redis.call('ZRANGE', k, 0, -1)) do
212        local sup = tonumber(redis.call('HGET', P .. 't:' .. hex, 'sup'))
213        if sup ~= nil and sup < cutoff then
214          redis.call('DEL', P .. 't:' .. hex)
215          redis.call('ZREM', k, hex)
216        end
217      end
218      rotated = 1
219    end
220  end
221end
222if ARGV[8] ~= '' then
223  local mk = P .. 't:' .. ARGV[8]
224  if redis.call('HGET', mk, 'sid') == sid and redis.call('HEXISTS', mk, 'used') == 0 then
225    redis.call('HSET', mk, 'used', now)
226  end
227end
228redis.call('HSET', s, 'seen', now)
229redis.call('ZADD', P .. 'i', now, sid)
230if ARGV[9] ~= '' then redis.call('HSET', s, 'baseline', ARGV[9]) end
231if ARGV[10] ~= '' then redis.call('HSET', s, 'step_up', ARGV[10]) end
232if ARGV[11] ~= '' then redis.call('HSET', s, 'auth', ARGV[11]) end
233return rotated
234",
235    )
236});
237
238/// KEYS: session. ARGV: bucket prefix, sid, expected subject (optional). Returns the deleted
239/// session's subject, or nothing when it did not exist or belongs to another subject.
240static DELETE: LazyLock<Script> = LazyLock::new(|| {
241    Script::new(concat!(
242        lua_helpers!(),
243        r"
244if ARGV[3] and redis.call('HGET', KEYS[1], 'subject') ~= ARGV[3] then return false end
245return del_session(ARGV[1], ARGV[2])
246",
247    ))
248});
249
250/// KEYS: expiry index. ARGV: bucket prefix, now, idle cutoff, batch size.
251static DELETE_EXPIRED: LazyLock<Script> = LazyLock::new(|| {
252    Script::new(concat!(
253        lua_helpers!(),
254        r"
255local P = ARGV[1]
256local found, n = 0, 0
257for _, idx in ipairs({{'x', ARGV[2]}, {'i', ARGV[3]}}) do
258  local ids = redis.call('ZRANGEBYSCORE', P .. idx[1], '-inf', idx[2], 'LIMIT', 0, ARGV[4])
259  found = found + #ids
260  for _, sid in ipairs(ids) do
261    if del_session(P, sid) then n = n + 1 end
262  end
263end
264return {n, found}
265",
266    ))
267});
268
269/// KEYS: events, claim index. ARGV: bucket prefix, cutoff.
270static DELETE_EVENTS: LazyLock<Script> = LazyLock::new(|| {
271    Script::new(
272        r"
273local bound = '(' .. ARGV[2]
274local n = redis.call('ZREMRANGEBYSCORE', KEYS[1], '-inf', bound)
275for _, m in ipairs(redis.call('ZRANGEBYSCORE', KEYS[2], '-inf', bound)) do
276  redis.call('DEL', ARGV[1] .. 'c:' .. m)
277end
278redis.call('ZREMRANGEBYSCORE', KEYS[2], '-inf', bound)
279return n
280",
281    )
282});
283
284/// KEYS: claim, claim index. ARGV: now, window (µs), window (ms), claim index member.
285static CLAIM: LazyLock<Script> = LazyLock::new(|| {
286    Script::new(
287        r"
288local at = tonumber(redis.call('GET', KEYS[1]))
289if at ~= nil and tonumber(ARGV[1]) - at < tonumber(ARGV[2]) then return 0 end
290redis.call('SET', KEYS[1], ARGV[1], 'PX', ARGV[3])
291redis.call('ZADD', KEYS[2], ARGV[1], ARGV[4])
292return 1
293",
294    )
295});
296
297/// Standalone or cluster connection behind one type, so the store has a single code path.
298#[derive(Clone)]
299enum Conn {
300    Standalone(ConnectionManager),
301    Cluster(ClusterConnection),
302}
303
304impl ConnectionLike for Conn {
305    fn req_packed_command<'a>(&'a mut self, cmd: &'a redis::Cmd) -> RedisFuture<'a, Value> {
306        match self {
307            Self::Standalone(conn) => conn.req_packed_command(cmd),
308            Self::Cluster(conn) => conn.req_packed_command(cmd),
309        }
310    }
311
312    fn req_packed_commands<'a>(
313        &'a mut self,
314        pipeline: &'a redis::Pipeline,
315        offset: usize,
316        count: usize,
317    ) -> RedisFuture<'a, Vec<Value>> {
318        match self {
319            Self::Standalone(conn) => conn.req_packed_commands(pipeline, offset, count),
320            Self::Cluster(conn) => conn.req_packed_commands(pipeline, offset, count),
321        }
322    }
323
324    fn get_db(&self) -> i64 {
325        match self {
326            Self::Standalone(conn) => conn.get_db(),
327            Self::Cluster(conn) => conn.get_db(),
328        }
329    }
330}
331
332/// A [`SessionStore`] on Valkey or Redis, standalone or Cluster.
333///
334/// Every write that touches more than one key runs as a Lua script, so it is atomic across any
335/// number of processes sharing the server. Requires Valkey 7.2+ or Redis 7.0+.
336///
337/// # Cluster
338///
339/// Connect with [`connect_cluster`](Self::connect_cluster) or
340/// [`from_cluster`](Self::from_cluster). Keys are split into 256 fixed buckets, and every key
341/// carries its bucket as a hash tag (`{bb}`), so a session, its tokens and its indexes always
342/// live in one hash slot and each script runs on one node. The bucket is the last byte of the
343/// session id, the first byte of a token's hash, or the first byte of the SHA-256 of a subject.
344/// [`Guard`](crate::Guard) mines tokens so that a session's tokens share its bucket; the store
345/// rejects writes where they do not.
346///
347/// The subject index is the one structure that spans buckets: a session id sits in its subject's
348/// set while the session lives in its own bucket, so subject-wide operations are eventually
349/// consistent. [`delete_subject_sessions`](SessionStore::delete_subject_sessions) moves the set
350/// aside, deletes each session in its bucket and then drops the moved ids. If the caller
351/// crashes in between, the leftover ids stay pending and the next revoke for the subject
352/// finishes them. A session created while a revoke runs is either revoked or its creator gets an
353/// error and the session is removed. [`list_subject_sessions`](SessionStore::list_subject_sessions)
354/// includes sessions that are mid-revoke.
355///
356/// [`delete_expired`](SessionStore::delete_expired) and
357/// [`delete_events_before`](SessionStore::delete_events_before) visit all 256 buckets.
358///
359/// # Data layout
360///
361/// All keys start with the [key prefix](Self::key_prefix) followed by the bucket tag, written
362/// `B` here (for example `sg:{0a}:`). Timestamps are microseconds since the Unix epoch as
363/// decimal integers.
364///
365/// | Key | Type | Contents |
366/// |-----|------|----------|
367/// | `B s:{session id}` | hash | `subject`, `created`, `auth`, `seen`, `expires`, `step_up`, `baseline` (JSON), `origin` (JSON, absent before 0.2), `cur` (current token), `seq` (token counter), `exp_ms` |
368/// | `B t:{token hash hex}` | hash | `sid`, `seq` (issue order), `issued`, `used`, `sup` (superseded) |
369/// | `B k:{session id}` | sorted set | the session's token hashes, scored by `seq` |
370/// | `B u:{subject}` | set | session ids of a subject (in the subject's bucket) |
371/// | `B ur:{subject}` | set | ids of a subject being revoked (in the subject's bucket) |
372/// | `B x` | sorted set | session ids scored by `expires_at` |
373/// | `B i` | sorted set | session ids scored by `last_seen_at` |
374/// | `B e` | sorted set | events as JSON, scored by `at` |
375/// | `B c:{session id}:{kind}` | string | time of the last session event claim |
376/// | `B c:s:{subject}:{kind}` | string | time of the last subject alert claim (subject's bucket) |
377/// | `B cz` | sorted set | `{session id}:{kind}` and `s:{subject}:{kind}` claims scored by claim time |
378///
379/// Session, token and per-session token-set keys expire at the session's absolute expiry and
380/// subject sets at their last session's expiry, so Valkey cleans up even if
381/// [`delete_expired`](SessionStore::delete_expired) never runs. Because those TTLs follow the
382/// server's wall clock, sessions whose `expires_at` is already in the past vanish immediately.
383/// Claim keys expire after their window.
384///
385/// Subjects are passed to scripts as data, never as code.
386///
387/// Cheap to clone; clones share the connection.
388#[derive(Clone)]
389pub struct ValkeyStore {
390    conn: Conn,
391    prefix: String,
392}
393
394impl fmt::Debug for ValkeyStore {
395    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
396        f.debug_struct("ValkeyStore")
397            .field("key_prefix", &self.prefix)
398            .finish_non_exhaustive()
399    }
400}
401
402impl ValkeyStore {
403    /// A store on an existing connection, with the default key prefix `sg:`.
404    pub fn new(conn: ConnectionManager) -> Self {
405        Self {
406            conn: Conn::Standalone(conn),
407            prefix: "sg:".to_owned(),
408        }
409    }
410
411    /// A store on an existing Cluster connection, with the default key prefix `sg:`.
412    pub fn from_cluster(conn: ClusterConnection) -> Self {
413        Self {
414            conn: Conn::Cluster(conn),
415            prefix: "sg:".to_owned(),
416        }
417    }
418
419    /// Connects to a Valkey or Redis Cluster through any of its nodes (`redis://`, `rediss://`
420    /// or `valkey://` URLs), with the default key prefix `sg:`.
421    ///
422    /// # Errors
423    ///
424    /// If a URL is invalid or no node is reachable.
425    pub async fn connect_cluster<T: redis::IntoConnectionInfo>(
426        nodes: impl IntoIterator<Item = T>,
427    ) -> Result<Self, redis::RedisError> {
428        let client = redis::cluster::ClusterClient::new(nodes)?;
429        Ok(Self::from_cluster(client.get_async_connection().await?))
430    }
431
432    /// Connects to `url` (`redis://`, `rediss://` or `valkey://`), with the default key prefix
433    /// `sg:`.
434    ///
435    /// # Errors
436    ///
437    /// If the URL is invalid or the server is unreachable.
438    pub async fn connect(url: &str) -> Result<Self, redis::RedisError> {
439        let client = redis::Client::open(url)?;
440        Ok(Self::new(ConnectionManager::new(client).await?))
441    }
442
443    /// Prefixes every key with `prefix`, so several apps can share one server. Defaults to
444    /// `sg:`.
445    ///
446    /// # Panics
447    ///
448    /// If `prefix` contains `{` or `}`: the store puts its own hash tag after the prefix, and a
449    /// brace in the prefix would change which slot keys land in.
450    #[must_use]
451    pub fn key_prefix(mut self, prefix: impl Into<String>) -> Self {
452        let prefix = prefix.into();
453        assert!(
454            !prefix.contains(['{', '}']),
455            "ValkeyStore key prefix must not contain '{{' or '}}'"
456        );
457        self.prefix = prefix;
458        self
459    }
460
461    /// `prefix{bb}:`, the start of every key in `bucket`.
462    fn bucket_prefix(&self, bucket: u8) -> String {
463        format!("{}{{{bucket:02x}}}:", self.prefix)
464    }
465
466    /// A key `kind:id` in `bucket`.
467    fn key(&self, bucket: u8, kind: &str, id: &str) -> String {
468        format!("{}{kind}:{id}", self.bucket_prefix(bucket))
469    }
470
471    /// A singleton key `kind` in `bucket`.
472    fn plain_key(&self, bucket: u8, kind: &str) -> String {
473        format!("{}{kind}", self.bucket_prefix(bucket))
474    }
475
476    fn conn(&self) -> Conn {
477        self.conn.clone()
478    }
479
480    /// Removes `session_id` from its subject's sets. Best effort: the sets also expire, and
481    /// readers tolerate ids of sessions that are gone.
482    async fn unindex(&self, subject: &str, session_id: Uuid) {
483        let bucket = subject_bucket(subject);
484        for kind in ["u", "ur"] {
485            let _removed: Result<i64, _> = redis::cmd("SREM")
486                .arg(self.key(bucket, kind, subject))
487                .arg(session_id.to_string())
488                .query_async(&mut self.conn())
489                .await;
490        }
491    }
492}
493
494/// The bucket of a subject's index sets: the first byte of the SHA-256 of its canonical JSON.
495fn subject_bucket(subject: &str) -> u8 {
496    Sha256::digest(subject.as_bytes())[0]
497}
498
499fn ensure_aligned(session_id: Uuid, token: &TokenHash) -> Result<(), StoreError> {
500    if session_bucket(session_id) == token_bucket(token) {
501        Ok(())
502    } else {
503        Err("valkey store: token and session id are in different buckets".into())
504    }
505}
506
507fn micros(at: OffsetDateTime) -> String {
508    unix_micros(at).to_string()
509}
510
511fn unix_micros(at: OffsetDateTime) -> i64 {
512    at.unix_timestamp() * 1_000_000 + i64::from(at.microsecond())
513}
514
515fn parse_time(value: &str) -> Result<OffsetDateTime, StoreError> {
516    value
517        .parse::<i64>()
518        .ok()
519        .and_then(|us| OffsetDateTime::from_unix_timestamp_nanos(i128::from(us) * 1000).ok())
520        .ok_or_else(|| "valkey store: malformed timestamp".into())
521}
522
523fn parse_optional_time(value: &str) -> Result<Option<OffsetDateTime>, StoreError> {
524    if value.is_empty() {
525        Ok(None)
526    } else {
527        parse_time(value).map(Some)
528    }
529}
530
531/// Parses the nine fields `read_session` returns.
532fn parse_session(fields: &[String]) -> Result<SessionRecord, StoreError> {
533    let [id, subject, created, auth, seen, expires, step_up, baseline, origin] = fields else {
534        return Err("valkey store: malformed session".into());
535    };
536    let baseline: Baseline = serde_json::from_str(baseline)?;
537    let origin: Option<SessionOrigin> = if origin.is_empty() {
538        None
539    } else {
540        Some(serde_json::from_str(origin)?)
541    };
542    Ok(SessionRecord {
543        id: Uuid::parse_str(id)?,
544        subject: subject.clone(),
545        created_at: parse_time(created)?,
546        authenticated_at: parse_time(auth)?,
547        last_seen_at: parse_time(seen)?,
548        expires_at: parse_time(expires)?,
549        step_up_required: step_up == "1",
550        baseline,
551        origin,
552    })
553}
554
555#[derive(Serialize)]
556struct EventRow<'a> {
557    /// Keeps identical events distinct in the sorted set.
558    id: Uuid,
559    session_id: Uuid,
560    subject: &'a str,
561    kind: EventKind,
562    enforced: bool,
563    score: Option<u32>,
564    signals: &'a [Check],
565    ip: IpAddr,
566    user_agent: Option<&'a str>,
567    client: &'a ClientSummary,
568    #[serde(with = "crate::rfc3339")]
569    at: OffsetDateTime,
570}
571
572impl SessionStore for ValkeyStore {
573    fn sharded(&self) -> bool {
574        true
575    }
576
577    async fn insert_session(&self, session: &SessionRecord, token: &TokenHash) -> Result<(), StoreError> {
578        ensure_aligned(session.id, token)?;
579        let bucket = session_bucket(session.id);
580        let sid = session.id.to_string();
581        let hex = token.to_hex();
582        let exp_ms = unix_micros(session.expires_at).saturating_add(999).div_euclid(1000);
583        // Index first: a concurrent revoke then either sees the id or makes the check below fail.
584        let sbucket = subject_bucket(&session.subject);
585        let _: i64 = INDEX_ADD
586            .key(self.key(sbucket, "u", &session.subject))
587            .arg(&sid)
588            .arg(exp_ms)
589            .invoke_async(&mut self.conn())
590            .await?;
591        let inserted: i64 = INSERT
592            .key(self.key(bucket, "s", &sid))
593            .key(self.key(bucket, "t", &hex))
594            .key(self.key(bucket, "k", &sid))
595            .key(self.plain_key(bucket, "x"))
596            .arg(self.bucket_prefix(bucket))
597            .arg(&sid)
598            .arg(&hex)
599            .arg(&session.subject)
600            .arg(micros(session.created_at))
601            .arg(micros(session.authenticated_at))
602            .arg(micros(session.last_seen_at))
603            .arg(micros(session.expires_at))
604            .arg(if session.step_up_required { "1" } else { "0" })
605            .arg(serde_json::to_string(&session.baseline)?)
606            .arg(exp_ms)
607            .arg(match &session.origin {
608                Some(origin) => serde_json::to_string(origin)?,
609                None => String::new(),
610            })
611            .invoke_async(&mut self.conn())
612            .await?;
613        if inserted != 1 {
614            return Err("duplicate session id or token".into());
615        }
616        let indexed: bool = redis::cmd("SISMEMBER")
617            .arg(self.key(sbucket, "u", &session.subject))
618            .arg(&sid)
619            .query_async(&mut self.conn())
620            .await?;
621        if !indexed {
622            let exists: bool = redis::cmd("EXISTS")
623                .arg(self.key(bucket, "s", &sid))
624                .query_async(&mut self.conn())
625                .await?;
626            if exists {
627                // A revoke moved the index entry between our two writes; do not leave a session
628                // the revoke can no longer find.
629                self.delete_session(session.id).await?;
630                return Err("valkey store: subject was revoked while the session was created".into());
631            }
632        }
633        Ok(())
634    }
635
636    async fn find_by_token(&self, token: &TokenHash) -> Result<Option<TokenLookup>, StoreError> {
637        let bucket = token_bucket(token);
638        let fields: Option<Vec<String>> = FIND
639            .key(self.key(bucket, "t", &token.to_hex()))
640            .arg(self.bucket_prefix(bucket))
641            .invoke_async(&mut self.conn())
642            .await?;
643        let Some(fields) = fields else {
644            return Ok(None);
645        };
646        let [session @ .., issued, used, superseded, newer] = fields.as_slice() else {
647            return Err("valkey store: malformed token lookup".into());
648        };
649        Ok(Some(TokenLookup {
650            session: parse_session(session)?,
651            token: TokenRecord {
652                hash: *token,
653                issued_at: parse_time(issued)?,
654                first_used_at: parse_optional_time(used)?,
655                superseded_at: parse_optional_time(superseded)?,
656            },
657            newer_token_used: newer == "1",
658        }))
659    }
660
661    async fn newer_used_tokens(&self, token: &TokenHash) -> Result<Option<Vec<TokenRecord>>, StoreError> {
662        let bucket = token_bucket(token);
663        let fields: Vec<String> = NEWER_USED
664            .key(self.key(bucket, "t", &token.to_hex()))
665            .arg(self.bucket_prefix(bucket))
666            .invoke_async(&mut self.conn())
667            .await?;
668        let tokens = fields
669            .chunks(4)
670            .map(|record| {
671                let [hex, issued, used, superseded] = record else {
672                    return Err("valkey store: malformed newer token list".into());
673                };
674                Ok(TokenRecord {
675                    hash: TokenHash::from_hex(hex).ok_or("valkey store: malformed token hash")?,
676                    issued_at: parse_time(issued)?,
677                    first_used_at: parse_optional_time(used)?,
678                    superseded_at: parse_optional_time(superseded)?,
679                })
680            })
681            .collect::<Result<Vec<_>, StoreError>>()?;
682        Ok(Some(tokens))
683    }
684
685    async fn apply(&self, update: &SessionUpdate) -> Result<bool, StoreError> {
686        if let Some(rotation) = &update.rotation {
687            ensure_aligned(update.session_id, &rotation.new_token)?;
688        }
689        if let Some(used) = &update.mark_used {
690            ensure_aligned(update.session_id, used)?;
691        }
692        let bucket = session_bucket(update.session_id);
693        let sid = update.session_id.to_string();
694        let (mode, mode_arg, new_token, prune) = match &update.rotation {
695            None => ("", String::new(), String::new(), String::new()),
696            Some(rotation) => {
697                let (mode, arg) = match rotation.supersede {
698                    Supersede::Exact(hash) => ("exact", hash.to_hex()),
699                    Supersede::CurrentIssuedBefore(at) => ("before", micros(at)),
700                    Supersede::Current => ("current", String::new()),
701                };
702                (
703                    mode,
704                    arg,
705                    rotation.new_token.to_hex(),
706                    micros(rotation.prune_superseded_before),
707                )
708            }
709        };
710        let baseline = match &update.baseline {
711            Some(baseline) => serde_json::to_string(baseline)?,
712            None => String::new(),
713        };
714        let step_up = match update.step_up_required {
715            Some(true) => "1",
716            Some(false) => "0",
717            None => "",
718        };
719        let rotated: i64 = APPLY
720            .key(self.key(bucket, "s", &sid))
721            .arg(self.bucket_prefix(bucket))
722            .arg(&sid)
723            .arg(micros(update.now))
724            .arg(mode)
725            .arg(mode_arg)
726            .arg(new_token)
727            .arg(prune)
728            .arg(update.mark_used.map(|h| h.to_hex()).unwrap_or_default())
729            .arg(baseline)
730            .arg(step_up)
731            .arg(update.authenticated_at.map(micros).unwrap_or_default())
732            .invoke_async(&mut self.conn())
733            .await?;
734        Ok(rotated == 1)
735    }
736
737    async fn delete_session(&self, session_id: Uuid) -> Result<bool, StoreError> {
738        let bucket = session_bucket(session_id);
739        let sid = session_id.to_string();
740        let subject: Option<String> = DELETE
741            .key(self.key(bucket, "s", &sid))
742            .arg(self.bucket_prefix(bucket))
743            .arg(&sid)
744            .invoke_async(&mut self.conn())
745            .await?;
746        let Some(subject) = subject else {
747            return Ok(false);
748        };
749        self.unindex(&subject, session_id).await;
750        Ok(true)
751    }
752
753    async fn delete_subject_sessions(&self, subject: &str) -> Result<Vec<Uuid>, StoreError> {
754        let sbucket = subject_bucket(subject);
755        let revoking = self.key(sbucket, "ur", subject);
756        let members: Vec<String> = INDEX_MOVE
757            .key(self.key(sbucket, "u", subject))
758            .key(&revoking)
759            .invoke_async(&mut self.conn())
760            .await?;
761        let mut deleted = Vec::new();
762        for member in &members {
763            // A malformed member can't name a session; the SREM below clears it.
764            let Ok(id) = Uuid::parse_str(member) else { continue };
765            let bucket = session_bucket(id);
766            let removed: Option<String> = DELETE
767                .key(self.key(bucket, "s", member))
768                .arg(self.bucket_prefix(bucket))
769                .arg(member)
770                .arg(subject)
771                .invoke_async(&mut self.conn())
772                .await?;
773            if removed.is_some() {
774                deleted.push(id);
775            }
776        }
777        // Only now are the ids done; a failure above leaves them pending for the next revoke.
778        for chunk in members.chunks(SREM_BATCH) {
779            let _removed: i64 = redis::cmd("SREM")
780                .arg(&revoking)
781                .arg(chunk)
782                .query_async(&mut self.conn())
783                .await?;
784        }
785        Ok(deleted)
786    }
787
788    async fn list_subject_sessions(&self, subject: &str) -> Result<Vec<SessionRecord>, StoreError> {
789        let sbucket = subject_bucket(subject);
790        let members: Vec<String> = redis::cmd("SUNION")
791            .arg(self.key(sbucket, "u", subject))
792            .arg(self.key(sbucket, "ur", subject))
793            .query_async(&mut self.conn())
794            .await?;
795        let mut sessions = Vec::with_capacity(members.len());
796        let mut stale = Vec::new();
797        for member in &members {
798            let Ok(id) = Uuid::parse_str(member) else {
799                stale.push(member);
800                continue;
801            };
802            let bucket = session_bucket(id);
803            let fields: Option<Vec<String>> = READ
804                .key(self.key(bucket, "s", member))
805                .arg(self.bucket_prefix(bucket))
806                .arg(member)
807                .invoke_async(&mut self.conn())
808                .await?;
809            match fields.map(|fields| parse_session(&fields)).transpose()? {
810                Some(record) if record.subject == subject => sessions.push(record),
811                _ => stale.push(member),
812            }
813        }
814        // Expired sessions leave their ids behind. Dropping one that a creator has added but
815        // not yet inserted is safe: the creator's membership check then fails the login.
816        for chunk in stale.chunks(SREM_BATCH) {
817            for kind in ["u", "ur"] {
818                let _removed: Result<i64, _> = redis::cmd("SREM")
819                    .arg(self.key(sbucket, kind, subject))
820                    .arg(chunk)
821                    .query_async(&mut self.conn())
822                    .await;
823            }
824        }
825        Ok(sessions)
826    }
827
828    async fn delete_expired(&self, now: OffsetDateTime, idle_cutoff: OffsetDateTime) -> Result<u64, StoreError> {
829        let mut total = 0;
830        for bucket in 0..=u8::MAX {
831            loop {
832                let (deleted, found): (u64, u64) = DELETE_EXPIRED
833                    .key(self.plain_key(bucket, "x"))
834                    .arg(self.bucket_prefix(bucket))
835                    .arg(micros(now))
836                    .arg(micros(idle_cutoff))
837                    .arg(PURGE_BATCH)
838                    .invoke_async(&mut self.conn())
839                    .await?;
840                total += deleted;
841                if found == 0 {
842                    break;
843                }
844            }
845        }
846        Ok(total)
847    }
848
849    async fn record_event(&self, event: &SessionEvent) -> Result<(), StoreError> {
850        let row = EventRow {
851            id: Uuid::new_v4(),
852            session_id: event.session_id,
853            subject: &event.subject,
854            kind: event.kind,
855            enforced: event.enforced,
856            score: event.score,
857            signals: &event.signals,
858            ip: event.ip,
859            user_agent: event.user_agent.as_deref(),
860            client: &event.client,
861            at: event.at,
862        };
863        let _added: i64 = redis::cmd("ZADD")
864            .arg(self.plain_key(session_bucket(event.session_id), "e"))
865            .arg(unix_micros(event.at))
866            .arg(serde_json::to_string(&row)?)
867            .query_async(&mut self.conn())
868            .await?;
869        Ok(())
870    }
871
872    async fn delete_events_before(&self, cutoff: OffsetDateTime) -> Result<u64, StoreError> {
873        let mut total = 0;
874        for bucket in 0..=u8::MAX {
875            let deleted: u64 = DELETE_EVENTS
876                .key(self.plain_key(bucket, "e"))
877                .key(self.plain_key(bucket, "cz"))
878                .arg(self.bucket_prefix(bucket))
879                .arg(micros(cutoff))
880                .invoke_async(&mut self.conn())
881                .await?;
882            total += deleted;
883        }
884        Ok(total)
885    }
886
887    async fn claim_event(
888        &self,
889        scope: ClaimScope<'_>,
890        kind: EventKind,
891        now: OffsetDateTime,
892        window: time::Duration,
893    ) -> Result<bool, StoreError> {
894        // A session id never starts with `s:`, and no kind contains `:`, so members are unique.
895        let (bucket, member) = match scope {
896            ClaimScope::Session(session_id) => (session_bucket(session_id), format!("{session_id}:{kind}")),
897            ClaimScope::Subject(subject) => (subject_bucket(subject), format!("s:{subject}:{kind}")),
898        };
899        let micros_window = i64::try_from(window.whole_microseconds()).unwrap_or(i64::MAX);
900        let millis_window = i64::try_from(window.whole_milliseconds()).unwrap_or(i64::MAX).max(1);
901        let claimed: i64 = CLAIM
902            .key(self.key(bucket, "c", &member))
903            .key(self.plain_key(bucket, "cz"))
904            .arg(micros(now))
905            .arg(micros_window)
906            .arg(millis_window)
907            .arg(&member)
908            .invoke_async(&mut self.conn())
909            .await?;
910        Ok(claimed == 1)
911    }
912}