security-rust 4.0.0

A pure Rust attack detection library with 32 detectors across 4 categories — injection, protocol, data, and file — plus stateful session, throttling, and risk scoring. Zero framework dependencies.
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
// Copyright (c) 2026 erik <erik@erik.xyz> — https://erik.xyz

use super::geo;
use super::store::{LoginPoint, SessionRecord, SessionStore};
use super::{
    RequestContext, SessionConfig, SessionError, SessionThreat, SessionVerdict, StoreError,
};

pub struct SessionGuard<S: SessionStore> {
    store: S,
    config: SessionConfig,
}

impl<S: SessionStore> SessionGuard<S> {
    pub fn new(store: S, config: SessionConfig) -> Self {
        Self { store, config }
    }

    pub fn config(&self) -> &SessionConfig {
        &self.config
    }

    /// 登录:建会话 + 绑指纹 + 记位置,并返回异地判定。
    ///
    /// 登录本身总是成功(除非调用方误用或后端故障)—— 异地只影响 verdict,
    /// 由调用方决定是否走二次验证,不应阻断登录。
    pub fn bind(&self, ctx: &RequestContext, now: u64) -> Result<SessionVerdict, SessionError> {
        if ctx.token.is_empty() {
            return Err(SessionError::EmptyToken);
        }
        if ctx.subject.is_empty() {
            return Err(SessionError::EmptySubject);
        }
        if ctx.fingerprint.is_empty() {
            return Err(SessionError::EmptyFingerprint);
        }

        // 坐标在信任边界校验一次:NaN / 越界一律降级为「没有坐标」,
        // 后面写入记录与登录历史的一律是这个清洗过的值
        let coords = geo::sanitize_coords(ctx.coords);

        let point = LoginPoint {
            location: ctx.location.map(str::to_string),
            coords,
            at: now,
        };

        // 异地判定必须在写入本次登录点之前取历史,否则会拿自己跟自己比
        let history = self.store.recent_logins(ctx.subject)?;

        let mut threats = Vec::new();
        if let Some(prev) = history.last() {
            if geo::location_changed(prev.location.as_deref(), ctx.location) {
                threats.push(SessionThreat::LocationChanged);
            }
            if let Some(kmh) =
                geo::impossible_travel(prev, &point, self.config.impossible_travel_kmh)
            {
                threats.push(SessionThreat::ImpossibleTravel { kmh });
            }
        }

        self.store.put(SessionRecord {
            token: ctx.token.to_string(),
            subject: ctx.subject.to_string(),
            fingerprint: ctx.fingerprint.to_string(),
            location: ctx.location.map(str::to_string),
            coords,
            signature: ctx.signature.map(str::to_string),
            issued_at: now,
            last_seen: now,
            expires_at: now.saturating_add(self.config.ttl_secs),
            revoked: false,
        })?;
        self.store.record_login(ctx.subject, point)?;

        Ok(SessionVerdict::from_threats(threats))
    }

    /// 每请求校验。
    ///
    /// 返回 `SessionVerdict` 而非 `Result`:认证路径上「拒绝」是正常结果而非错误,
    /// 强制调用方在类型层面处理每一种拒绝。
    ///
    /// `get` → `recent_logins` → `touch` 是三次独立锁获取,**不原子**(与
    /// `throttle::Throttle::record_failure` 的窗口说明同一取舍):并发下
    /// `touch` 可能落在一条刚被 revoke / purge 掉的记录上(落空,无副作用),
    /// 登录历史也可能读到略旧的一份。这不构成绕过 —— 各判定只吃自己那一份
    /// 快照(`get` 返回的是克隆),没有跨字段的复合不变量会被撕开;
    /// 要消除这个窗口得把「读记录 + 读历史 + 刷新 last_seen」并成一个 store 操作。
    pub fn verify(&self, ctx: &RequestContext, now: u64) -> SessionVerdict {
        // ── 门槛检查:记录不存在或不可读时,后续检查没有基线可比,必须提前退出 ──
        if ctx.token.is_empty() {
            return SessionVerdict::single(SessionThreat::TokenUnknown);
        }

        let record = match self.store.get(ctx.token) {
            Ok(Some(r)) => r,
            Ok(None) => return SessionVerdict::single(SessionThreat::TokenUnknown),
            // fail-closed:后端故障时放行所有请求是一个可被攻击者主动触发的绕过
            Err(_) => return SessionVerdict::single(SessionThreat::StoreUnavailable),
        };

        if record.revoked {
            return SessionVerdict::single(SessionThreat::TokenRevoked);
        }
        if record.expires_at <= now {
            return SessionVerdict::single(SessionThreat::TokenExpired);
        }

        self.verify_binding(ctx, &record, now)
    }

    /// 累积检查:需要有效基线,逐项收集而非提前退出,以便日志与取证完整。
    fn verify_binding(
        &self,
        ctx: &RequestContext,
        record: &SessionRecord,
        now: u64,
    ) -> SessionVerdict {
        let mut threats = Vec::new();

        // 劫持:指纹不符
        if !ct_eq(record.fingerprint.as_bytes(), ctx.fingerprint.as_bytes()) {
            threats.push(SessionThreat::FingerprintMismatch);
        }

        // 篡改:签名比对
        match (record.signature.as_deref(), ctx.signature) {
            (Some(stored), Some(current)) if !ct_eq(stored.as_bytes(), current.as_bytes()) => {
                threats.push(SessionThreat::SignatureInvalid);
            }
            (Some(_), None) => threats.push(SessionThreat::SignatureMissing),
            // 登录时没设基线,本次却带了签名:请求方与会话建立方行为不一致
            (None, Some(_)) => threats.push(SessionThreat::SignatureUnexpected),
            _ => {}
        }

        // 重放:请求自称时间偏离窗口
        if ctx
            .at
            .is_some_and(|at| now.abs_diff(at) > self.config.timestamp_skew_secs)
        {
            threats.push(SessionThreat::TimestampSkew);
        }

        // 异地:与会话记录的位置比对
        if geo::location_changed(record.location.as_deref(), ctx.location) {
            threats.push(SessionThreat::LocationChanged);
        }

        // 异地(铁证):与该身份的登录历史比对
        match self.store.recent_logins(&record.subject) {
            Ok(history) => {
                let current = LoginPoint {
                    location: ctx.location.map(str::to_string),
                    coords: geo::sanitize_coords(ctx.coords),
                    at: now,
                };
                if let Some(kmh) = history.last().and_then(|prev| {
                    geo::impossible_travel(prev, &current, self.config.impossible_travel_kmh)
                }) {
                    threats.push(SessionThreat::ImpossibleTravel { kmh });
                }
            }
            // fail-closed:历史读不到时静默跳过,等于「后端一坏,异地检测就关」,
            // 攻击者可以用后端故障(或诱导故障)换掉一整类判定。上报为
            // StoreUnavailable(⇒ Block),与 bind() 对同一调用用 `?`、
            // verify() 把 get 的 Err 转 StoreUnavailable 的处置保持一致。
            Err(_) => threats.push(SessionThreat::StoreUnavailable),
        }

        if threats.is_empty() {
            // 只有放行时才刷新 last_seen:被拦的请求不该留下「刚刚还活跃」的观测。
            // 注意这只影响 last_seen 这一个观测值 —— `expires_at` 只在 bind / rotate
            // 写入、verify 从不延长,TTL 是绝对的,因此这里与「会话寿命」无关。
            let _ = self.store.touch(ctx.token, now);
            return SessionVerdict::allow();
        }

        SessionVerdict::from_threats(threats)
    }

    /// 吊销单个会话(登出)。
    pub fn revoke(&self, token: &str) -> Result<(), StoreError> {
        self.store.revoke(token)
    }

    /// 吊销某 subject 的全部会话(改密码 / 踢下线),返回受影响条数。
    pub fn revoke_all(&self, subject: &str) -> Result<usize, StoreError> {
        self.store.revoke_subject(subject)
    }

    /// 续期换 token:旧 token 吊销,新 token 由调用方提供。
    ///
    /// 旧会话必须存在、未吊销、未过期,**且指纹与本次 ctx 相符** ——
    /// 否则等于允许攻击者拿别人的 token 换一个自己的新 token,是提权漏洞。
    ///
    /// **前置条件:`new` 必须是一个未在用的 token**(不存在,或已过期,或已吊销
    /// —— 死记录可以覆盖)。指向一个在用会话返回 [`SessionError::TokenInUse`]
    /// 且不改动任何记录:store 的 `put` 是无条件 upsert,不挡这一下就等于让
    /// 攻击者用自己的会话把受害者的记录整个盖掉(受害者下次 verify 读到的是
    /// 攻击者的指纹 ⇒ 被动踢下线)。`new == old` 同样按 `TokenInUse` 拒绝 ——
    /// 它自相矛盾(既要吊销 old 又要 new 可用),静默接受只会得到一个
    /// 「rotate 成功但会话已死」的假象。
    ///
    /// 新记录的身份字段(subject / location / coords / signature)一律
    /// 以服务端记录为准,不接受 `ctx` 覆盖。
    ///
    /// **TOCTOU**:查 `new` 与随后的 `put` 是两次独立锁获取,**不原子** ——
    /// 两个并发 rotate 指向同一个新 token 时仍可能互相覆盖(要攻击者猜到对方
    /// 的新 token 并卡进这个窄窗)。本 trait 没有条件写 / 事务,这个检查把
    /// 「必然覆盖」降级为「窄窗竞争」,仍然值得;要彻底关窗得加 `put_if_absent`
    /// 一类的原子原语。
    pub fn rotate(
        &self,
        old: &str,
        new: &str,
        ctx: &RequestContext,
        now: u64,
    ) -> Result<(), SessionError> {
        if old.is_empty() || new.is_empty() {
            return Err(SessionError::EmptyToken);
        }

        let record = match self.store.get(old)? {
            Some(r) if !r.revoked && r.expires_at > now => r,
            _ => return Err(SessionError::UnknownSession),
        };

        if !ct_eq(record.fingerprint.as_bytes(), ctx.fingerprint.as_bytes()) {
            return Err(SessionError::UnknownSession);
        }

        // 「在用」与上面判 old 口径一致:存在 && 未吊销 && 未过期。
        // 放在指纹校验之后:先确认调用方有权动这个旧会话,再谈新 token 能不能用。
        // 命中即返回,此时还没有任何写入 —— 失败的 rotate 不留副作用。
        if let Some(target) = self.store.get(new)?
            && !target.revoked
            && target.expires_at > now
        {
            return Err(SessionError::TokenInUse);
        }

        self.store.put(SessionRecord {
            token: new.to_string(),
            issued_at: now,
            last_seen: now,
            expires_at: now.saturating_add(self.config.ttl_secs),
            revoked: false,
            ..record
        })?;
        // 旧 token 立即失效
        self.store.revoke(old)?;

        Ok(())
    }

    /// 清除已过期记录,返回清除条数。
    ///
    /// 内存后端无后台线程,map 条目只增不减;长期运行的进程需按 `ttl_secs`
    /// 量级的间隔定时调用(同时回收休眠 subject 的登录历史,见
    /// [`LOGIN_HISTORY_KEEP_SECS`](super::store::LOGIN_HISTORY_KEEP_SECS))。
    pub fn purge_expired(&self, now: u64) -> Result<usize, StoreError> {
        self.store.purge_expired(now)
    }
}

/// 常数时间字节比较。
///
/// 用于比对 MAC / 指纹 —— 直接用 `==` 比较会在首个不同字节处提前返回,
/// 泄露「前 N 个字节猜对了」的时序信息。
///
/// 长度不同立即返回 `false`:长度会泄露,但长度本身不敏感,这是通行做法。
/// `black_box` 阻止优化器把累积循环改写成提前退出。
pub(crate) fn ct_eq(a: &[u8], b: &[u8]) -> bool {
    if a.len() != b.len() {
        return false;
    }
    let mut diff = 0u8;
    for (x, y) in a.iter().zip(b.iter()) {
        diff |= x ^ y;
    }
    std::hint::black_box(diff) == 0
}

#[cfg(test)]
mod tests {
    use super::super::Decision;
    use super::super::store::{LOGIN_HISTORY_KEEP_SECS, MemoryStore};
    use super::*;

    const NOW: u64 = 1_000_000;
    const FP: &str = "ip=1.2.3.4|ua=curl";

    fn ctx<'a>(token: &'a str, subject: &'a str, fp: &'a str) -> RequestContext<'a> {
        RequestContext {
            token,
            subject,
            fingerprint: fp,
            location: Some("CN-BJ"),
            coords: Some((39.9042, 116.4074)),
            signature: None,
            at: None,
        }
    }

    fn guard() -> SessionGuard<MemoryStore> {
        SessionGuard::new(MemoryStore::new(), SessionConfig::default())
    }

    // 这些测试要读 `guard.store` 的私有字段,因此留在单测里;
    // 纯公开 API 的行为测试(含 fail-closed、误报防护)在 tests/session*.rs。

    #[test]
    fn ct_eq_equal() {
        assert!(ct_eq(b"abc123", b"abc123"));
    }

    #[test]
    fn ct_eq_empty_is_equal() {
        assert!(ct_eq(b"", b""));
    }

    #[test]
    fn ct_eq_single_byte_difference() {
        assert!(!ct_eq(b"abc123", b"abc124"));
        // 首字节不同
        assert!(!ct_eq(b"abc123", b"zbc123"));
    }

    #[test]
    fn ct_eq_long_common_prefix_still_differs() {
        let a = vec![7u8; 4096];
        let mut b = a.clone();
        b[4095] = 8;
        assert!(!ct_eq(&a, &b));
    }

    #[test]
    fn ct_eq_length_mismatch() {
        assert!(!ct_eq(b"abc", b"abcd"));
        assert!(!ct_eq(b"", b"a"));
    }

    #[test]
    fn ct_eq_non_ascii_bytes() {
        assert!(ct_eq("签名".as_bytes(), "签名".as_bytes()));
        assert!(!ct_eq("签名".as_bytes(), "签名!".as_bytes()));
    }

    #[test]
    fn ct_eq_differs_only_in_last_byte_of_each_length() {
        // 累积或运算保证:即使差异出现在末尾也返回 false,不会被优化成提前退出
        for len in [1usize, 2, 3, 16, 32, 256] {
            let a = vec![0u8; len];
            let mut b = a.clone();
            b[len - 1] = 1;
            assert!(!ct_eq(&a, &b), "len {len}");
        }
    }

    #[test]
    fn guard_is_generic_over_store() {
        // SessionGuard 只绑定 SessionStore trait,便于多实例部署换后端
        let g = SessionGuard::new(MemoryStore::new(), SessionConfig::default());
        assert_eq!(g.config().ttl_secs, 3600);
        assert_eq!(g.config().impossible_travel_kmh, 900.0);
        assert_eq!(g.config().timestamp_skew_secs, 300);
    }

    #[test]
    fn bind_creates_session_record() {
        let g = guard();
        let v = g.bind(&ctx("t1", "u1", FP), NOW).unwrap();
        assert!(v.is_allowed(), "首登无历史,不该报异地: {:?}", v.threats);
        let r = g.store.get("t1").unwrap().expect("record created");
        assert_eq!(r.subject, "u1");
        assert_eq!(r.fingerprint, FP);
        assert_eq!(r.issued_at, NOW);
        assert_eq!(r.last_seen, NOW);
        assert_eq!(r.expires_at, NOW + 3600);
        assert!(!r.revoked);
    }

    #[test]
    fn bind_records_login_point() {
        let g = guard();
        g.bind(&ctx("t1", "u1", FP), NOW).unwrap();
        let h = g.store.recent_logins("u1").unwrap();
        assert_eq!(h.len(), 1);
        assert_eq!(h[0].location.as_deref(), Some("CN-BJ"));
        assert_eq!(h[0].at, NOW);
    }

    #[test]
    fn bind_drops_non_finite_coords_at_trust_boundary() {
        // NaN 一旦入库/入历史就会长期污染该 subject 的异地判定,必须在入口清洗
        let g = guard();
        let mut bad = ctx("t1", "u1", FP);
        bad.coords = Some((f64::NAN, 116.4074));
        g.bind(&bad, NOW).unwrap();
        assert_eq!(g.store.get("t1").unwrap().unwrap().coords, None);
        assert_eq!(g.store.recent_logins("u1").unwrap()[0].coords, None);

        // 合法坐标照常保留
        let mut good = ctx("t2", "u2", FP);
        good.coords = Some((31.2304, 121.4737));
        g.bind(&good, NOW).unwrap();
        assert_eq!(
            g.store.get("t2").unwrap().unwrap().coords,
            Some((31.2304, 121.4737))
        );
    }

    #[test]
    fn bind_stores_signature_baseline() {
        let g = guard();
        let mut c = ctx("t1", "u1", FP);
        c.signature = Some("mac-abc");
        g.bind(&c, NOW).unwrap();
        assert_eq!(
            g.store.get("t1").unwrap().unwrap().signature.as_deref(),
            Some("mac-abc")
        );
    }

    #[test]
    fn bind_honours_custom_ttl() {
        let g = SessionGuard::new(
            MemoryStore::new(),
            SessionConfig {
                ttl_secs: 60,
                ..Default::default()
            },
        );
        g.bind(&ctx("t1", "u1", FP), NOW).unwrap();
        assert_eq!(g.store.get("t1").unwrap().unwrap().expires_at, NOW + 60);
    }

    #[test]
    fn verify_refreshes_last_seen_only_when_allowed() {
        let g = guard();
        g.bind(&ctx("t1", "u1", FP), NOW).unwrap();
        assert!(g.verify(&ctx("t1", "u1", FP), NOW + 10).is_allowed());
        assert_eq!(g.store.get("t1").unwrap().unwrap().last_seen, NOW + 10);
    }

    #[test]
    fn verify_does_not_refresh_last_seen_when_blocked() {
        let g = guard();
        g.bind(&ctx("t1", "u1", FP), NOW).unwrap();
        let v = g.verify(&ctx("t1", "u1", "ATTACKER-FP"), NOW + 10);
        assert_eq!(v.decision, Decision::Block);
        assert_eq!(
            g.store.get("t1").unwrap().unwrap().last_seen,
            NOW,
            "被拦的请求不该刷新 last_seen 观测(TTL 绝对,本就不受影响)"
        );
    }

    #[test]
    fn purge_expired_reaches_the_store() {
        let g = guard();
        g.bind(&ctx("t1", "u1", FP), NOW).unwrap();

        // 未过期:会话与登录历史都留着
        assert_eq!(g.purge_expired(NOW).unwrap(), 0);
        assert!(g.store.get("t1").unwrap().is_some());

        // 过期后:委派真的落到了 store 上 —— 会话被清,休眠的登录历史也被回收
        let later = NOW + 3_600 + LOGIN_HISTORY_KEEP_SECS + 1;
        assert_eq!(g.purge_expired(later).unwrap(), 1);
        assert!(g.store.get("t1").unwrap().is_none());
        assert!(g.store.recent_logins("u1").unwrap().is_empty());
    }

    #[test]
    fn rotate_issues_new_token_and_kills_old() {
        let g = guard();
        g.bind(&ctx("old", "u1", FP), NOW).unwrap();
        g.rotate("old", "new", &ctx("old", "u1", FP), NOW + 10)
            .unwrap();

        assert_eq!(
            g.verify(&ctx("old", "u1", FP), NOW + 20).threats,
            vec![SessionThreat::TokenRevoked]
        );
        // 新 token 可用,且继承 subject / 指纹 / 位置基线
        let v = g.verify(&ctx("new", "u1", FP), NOW + 20);
        assert!(v.is_allowed(), "got {:?}", v.threats);
        let r = g.store.get("new").unwrap().unwrap();
        assert_eq!(r.subject, "u1");
        assert_eq!(r.fingerprint, FP);
        assert_eq!(r.location.as_deref(), Some("CN-BJ"));
    }

    #[test]
    fn rotate_refreshes_ttl() {
        let g = guard();
        g.bind(&ctx("old", "u1", FP), NOW).unwrap();
        g.rotate("old", "new", &ctx("old", "u1", FP), NOW + 1_000)
            .unwrap();
        assert_eq!(
            g.store.get("new").unwrap().unwrap().expires_at,
            NOW + 1_000 + 3_600
        );
    }

    #[test]
    fn rotate_ignores_ctx_subject_and_uses_record_subject() {
        // subject 以服务端记录为准,不能被请求方覆盖
        let g = guard();
        g.bind(&ctx("old", "u1", FP), NOW).unwrap();
        g.rotate("old", "new", &ctx("old", "VICTIM", FP), NOW + 10)
            .unwrap();
        assert_eq!(g.store.get("new").unwrap().unwrap().subject, "u1");
    }

    #[test]
    fn rotate_rejects_collision_with_live_token() {
        // 攻击者拿自己的活跃会话把新 token 指向受害者的 token:不挡这一下,
        // 无条件 upsert 的 put 会整条盖掉受害者记录,受害者下次 verify 就
        // 读到自己记录上的攻击者指纹 ⇒ 被动踢下线
        const VFP: &str = "ip=5.6.7.8|ua=safari";
        let g = guard();
        g.bind(&ctx("victim-token", "victim", VFP), NOW).unwrap();
        g.bind(&ctx("attacker-old", "attacker", FP), NOW).unwrap();

        assert_eq!(
            g.rotate(
                "attacker-old",
                "victim-token",
                &ctx("attacker-old", "attacker", FP),
                NOW + 10
            )
            .unwrap_err(),
            SessionError::TokenInUse
        );

        // 受害者记录一字未动:还是他自己的 subject / 指纹,且仍然放行
        let r = g.store.get("victim-token").unwrap().unwrap();
        assert_eq!(r.subject, "victim");
        assert_eq!(r.fingerprint, VFP);
        assert!(!r.revoked);
        assert!(
            g.verify(&ctx("victim-token", "victim", VFP), NOW + 20)
                .is_allowed()
        );
        // 失败的 rotate 不留副作用:攻击者自己的旧会话也照旧可用
        assert!(
            g.verify(&ctx("attacker-old", "attacker", FP), NOW + 20)
                .is_allowed()
        );
    }

    #[test]
    fn rotate_may_reuse_a_revoked_token() {
        // 死记录(已吊销)不是「在用」,可以覆盖:登出后留下的记录不该永久占坑
        let g = guard();
        g.bind(&ctx("dead", "u1", FP), NOW).unwrap();
        g.revoke("dead").unwrap();
        g.bind(&ctx("old", "u2", FP), NOW).unwrap();

        g.rotate("old", "dead", &ctx("old", "u2", FP), NOW + 10)
            .unwrap();
        let r = g.store.get("dead").unwrap().unwrap();
        assert_eq!(r.subject, "u2");
        assert!(!r.revoked, "覆盖后是全新记录,revoked 不继承");
        assert_eq!(r.expires_at, NOW + 10 + 3_600);
    }

    #[test]
    fn rotate_may_reuse_an_expired_token() {
        // stale 过期于 NOW+3600;old 晚 1 秒签发(过期于 NOW+3601),
        // 好让它在下面的边界时刻仍然活着可轮换
        let g = guard();
        g.bind(&ctx("stale", "u1", FP), NOW).unwrap();
        g.bind(&ctx("old", "u2", FP), NOW + 1).unwrap();

        // 边界内(expires_at > now 仍为真)→ 在用,拒绝
        assert_eq!(
            g.rotate("old", "stale", &ctx("old", "u2", FP), NOW + 3_599)
                .unwrap_err(),
            SessionError::TokenInUse
        );

        // expires_at == now → 已过期(与 verify 的 `expires_at <= now` 同一口径),可以覆盖
        g.rotate("old", "stale", &ctx("old", "u2", FP), NOW + 3_600)
            .unwrap();
        let r = g.store.get("stale").unwrap().unwrap();
        assert_eq!(r.subject, "u2");
        assert_eq!(r.expires_at, NOW + 3_600 + 3_600);
    }

    #[test]
    fn rotate_to_the_same_token_is_rejected_and_session_survives() {
        // new == old 自相矛盾:既要吊销 old 又要 new 可用。旧实现 put 完立刻
        // revoke,返回 Ok 而会话已死 —— 调用方以为续期成功,用户却被登出。
        // 拒绝且零副作用,让这种调用当场暴露而不是静默失效。
        let g = guard();
        g.bind(&ctx("t", "u1", FP), NOW).unwrap();

        assert_eq!(
            g.rotate("t", "t", &ctx("t", "u1", FP), NOW + 10)
                .unwrap_err(),
            SessionError::TokenInUse
        );

        let r = g.store.get("t").unwrap().unwrap();
        assert!(!r.revoked, "失败的 rotate 不能有副作用");
        assert_eq!(r.expires_at, NOW + 3_600, "TTL 也不该被续期");
        assert_eq!(r.last_seen, NOW);
        assert!(g.verify(&ctx("t", "u1", FP), NOW + 20).is_allowed());
    }
}