seshcookie 0.1.0

Stateless, encrypted, type-safe session cookies for Rust web applications.
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
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
//! Per-request session state and the pure decision function used on the response path.
//!
//! pattern: Functional Core
//!
//! `SessionState<T>` holds the typed payload, an `issued_at` timestamp, the SHA-256 of
//! the layer-1 plaintext observed on entry, the zero-based index of the decrypt key that
//! succeeded (or `None` if no cookie), and mutation bookkeeping. The response path calls
//! `should_rewrite` to decide whether to emit a fresh cookie, emit a cookie-delete, or
//! skip — with full support for rotation migration and opt-in sliding refresh.
//!
//! This module is part of the Functional Core: every public function is
//! synchronous, takes the current time as an explicit `now: SystemTime`
//! parameter, and produces deterministic output from its inputs alone — no
//! wall-clock reads, no I/O, no randomness. The [`crate::SessionLayer`]'s
//! `SessionService` (the Imperative Shell) supplies `now`, calls these functions,
//! and is responsible for any HTTP-level side effects.

use std::time::{Duration, SystemTime};

use serde::Serialize;

use crate::envelope;

/// Per-request state. Wrapped in `Arc<tokio::sync::Mutex<_>>` by Phase 3's
/// `SessionService` so that the `Session<T>` extractor (Phase 4) can mutate
/// `payload` and `mutated` via its async handle methods without requiring a
/// blocking mutex.
///
/// `Debug` is implemented manually (not derived) so the payload bytes never
/// enter a trace log. Consumers whose `T` does not itself implement `Debug`
/// can still use this crate — no `T: Debug` bound leaks.
pub(crate) struct SessionState<T> {
    /// The currently-held typed session payload, or `None` if the request had
    /// no cookie, the cookie was malformed, the cookie was expired, or the
    /// handler called `session.clear()`.
    pub(crate) payload: Option<T>,
    /// The session's `issued_at` timestamp. For continuing sessions this is
    /// the value decoded from the incoming cookie. For brand-new sessions
    /// constructed after a no-cookie request, this field is placeholder-only
    /// — `should_rewrite` overrides it to `now` when computing the candidate
    /// plaintext.
    pub(crate) issued_at: SystemTime,
    /// SHA-256 of the layer-1 plaintext (`version || issued_at || payload_json`)
    /// decoded on entry. `None` if no cookie was present on the request. Used
    /// by `should_rewrite` to suppress no-op rewrites — when a mutated
    /// candidate plaintext hashes to the same value, no `Set-Cookie` is
    /// emitted.
    pub(crate) original_plaintext_hash: Option<[u8; 32]>,
    /// Zero-based index of the rotation key that decrypted the cookie, or
    /// `None` if no cookie was present or decryption failed. A non-zero index
    /// triggers an auto-migrate rewrite with the primary key.
    pub(crate) decrypt_key_index: Option<usize>,
    /// Set speculatively by `Session<T>` handle methods that mutate the
    /// payload (`insert`, `take`, `clear`, `modify`). A `true` value does not
    /// by itself force a rewrite — `should_rewrite` still performs the
    /// hash-compare.
    pub(crate) mutated: bool,
    /// Forces a rewrite regardless of hash-compare. Set by `from_decrypt`
    /// when the cookie was decrypted with a non-primary key (rotation
    /// migration) or was expired (stale-cleanup delete emission in the
    /// decision function). Also set by the sliding-refresh branch of
    /// `should_rewrite` (added in Task 2).
    pub(crate) needs_rewrite: bool,
}

/// Cookie contents fully decoded on the request path. Phase 3 builds this
/// from the output of `codec::decode_cookie` plus
/// `serde_json::from_slice::<T>` on the returned payload bytes.
/// `plaintext_hash` is SHA-256 of the **layer-1 plaintext bytes** (`version
/// || issued_at || payload_json`), not the ciphertext or the cookie value.
///
/// `Debug` is implemented manually so the `payload` field never renders in
/// trace logs.
pub(crate) struct DecodedCookie<T> {
    pub(crate) payload: T,
    pub(crate) issued_at: SystemTime,
    pub(crate) plaintext_hash: [u8; 32],
    pub(crate) decrypt_key_index: usize,
}

impl<T> std::fmt::Debug for SessionState<T> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("SessionState")
            .field("payload", &self.payload.as_ref().map(|_| "<redacted>"))
            .field("issued_at", &self.issued_at)
            .field(
                "original_plaintext_hash",
                &self.original_plaintext_hash.is_some(),
            )
            .field("decrypt_key_index", &self.decrypt_key_index)
            .field("mutated", &self.mutated)
            .field("needs_rewrite", &self.needs_rewrite)
            .finish()
    }
}

impl<T> std::fmt::Debug for DecodedCookie<T> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("DecodedCookie")
            .field("payload", &"<redacted>")
            .field("issued_at", &self.issued_at)
            .field("plaintext_hash", &"<32 bytes>")
            .field("decrypt_key_index", &self.decrypt_key_index)
            .finish()
    }
}

/// Outcome of `should_rewrite`. Phase 3's `SessionService` response path
/// maps each variant to a concrete `Set-Cookie` header (or the absence
/// thereof).
#[derive(Debug)]
pub(crate) enum RewriteAction {
    /// Do nothing — no `Set-Cookie` header.
    None,
    /// Emit a `Set-Cookie` whose encrypted value is `plaintext` sealed with
    /// the primary key. `issued_at` is already inside `plaintext` and is
    /// returned alongside for diagnostics (Phase 3 tracing may log it).
    Emit {
        plaintext: Vec<u8>,
        issued_at: SystemTime,
    },
    /// Emit a cookie-delete: empty value, `Max-Age = 0`, `Expires` in the
    /// past, same `Path`/`Domain` as a regular `Set-Cookie`.
    Delete,
}

impl<T> SessionState<T> {
    /// Build an empty state (no session payload, no prior cookie). The
    /// `issued_at` field carries `now` as a placeholder; `should_rewrite`
    /// substitutes its own `now` when computing the candidate plaintext for
    /// a brand-new session.
    pub(crate) fn new_empty(now: SystemTime) -> Self {
        Self {
            payload: None,
            issued_at: now,
            original_plaintext_hash: None,
            decrypt_key_index: None,
            mutated: false,
            needs_rewrite: false,
        }
    }

    /// Build state from the Phase-3 request path.
    ///
    /// - `decoded = None` → no cookie was present (or it was malformed /
    ///   base64-bad / AEAD-failed / JSON-bad-for-`T`). Returns an empty
    ///   state; the response path will emit nothing unless the handler
    ///   creates a new session.
    /// - `decoded = Some(d)` and `d.issued_at + max_age < now` → expired.
    ///   Returns a state with `payload = None`, `original_plaintext_hash =
    ///   Some(d.plaintext_hash)` (so the response path knows a cookie was
    ///   present to delete), and `needs_rewrite = true` per the design plan's
    ///   decision-table encoding.
    /// - `decoded = Some(d)` and not expired → returns a state with
    ///   `payload = Some(d.payload)`, preserves `issued_at`, stores the hash
    ///   and key index, and sets `needs_rewrite = d.decrypt_key_index != 0`
    ///   (rotation migration).
    ///
    /// The expiry check uses `checked_add` on the issued-at timestamp so that
    /// a `max_age` so large it would overflow `SystemTime` is treated as
    /// "effectively no expiry" (no panic, no premature rejection).
    pub(crate) fn from_decrypt(
        decoded: Option<DecodedCookie<T>>,
        max_age: Duration,
        now: SystemTime,
    ) -> Self {
        match decoded {
            None => Self::new_empty(now),
            Some(d) => {
                let expired = match d.issued_at.checked_add(max_age) {
                    Some(expiry) => now > expiry,
                    None => false,
                };
                if expired {
                    Self {
                        // payload is dropped; an expired cookie cannot be
                        // surfaced to the handler. The response path will
                        // emit a delete to clean up the stale browser cookie.
                        payload: None,
                        issued_at: now,
                        original_plaintext_hash: Some(d.plaintext_hash),
                        decrypt_key_index: Some(d.decrypt_key_index),
                        mutated: false,
                        needs_rewrite: true,
                    }
                } else {
                    Self {
                        payload: Some(d.payload),
                        issued_at: d.issued_at,
                        original_plaintext_hash: Some(d.plaintext_hash),
                        decrypt_key_index: Some(d.decrypt_key_index),
                        mutated: false,
                        // Any non-primary key triggers an auto-migrate
                        // rewrite (handled in Task 2's `should_rewrite`).
                        needs_rewrite: d.decrypt_key_index != 0,
                    }
                }
            }
        }
    }
}

/// SHA-256 of the supplied bytes. Returned as a 32-byte array so it can be
/// stored by value inside `SessionState` without heap allocation.
pub(crate) fn sha256(bytes: &[u8]) -> [u8; 32] {
    let digest = ring::digest::digest(&ring::digest::SHA256, bytes);
    let mut out = [0u8; 32];
    out.copy_from_slice(digest.as_ref());
    out
}

/// Pure decision: given the current `SessionState` and the time/refresh
/// policy, return what the response path should emit.
///
/// # Decision table
///
/// Evaluated top-to-bottom. Each row corresponds to one logical case in the
/// design plan's rewrite-discipline section.
///
/// 1. `state.payload = None` and `state.original_plaintext_hash = Some(_)` →
///    [`RewriteAction::Delete`]. The browser holds a cookie that is no longer
///    valid: the handler called `clear()` on a valid cookie, the cookie was
///    expired at ingress and `from_decrypt` parked us here, or the cookie
///    decrypted but failed JSON deserialization for `T`. In every case the
///    browser's copy must be invalidated.
///
/// 2. `state.payload = None` and `state.original_plaintext_hash = None` →
///    [`RewriteAction::None`]. There was no session on entry and there is
///    none on exit (the handler never touched `Session<T>`, or it called
///    `session.clear()` on a request that had no cookie).
///
/// 3. `state.payload = Some(_)`. Compute a candidate layer-1 plaintext using
///    `effective_issued_at`:
///
///    - When `state.original_plaintext_hash = None` (brand-new session, no
///      prior cookie), `effective_issued_at = now`.
///    - Otherwise (continuing session), `effective_issued_at =
///      state.issued_at`.
///
///    Then evaluate the sliding-refresh branch: when `refresh_after =
///    Some(threshold)` and `now - effective_issued_at` is strictly greater
///    than `threshold` and strictly less than `max_age`, set
///    `effective_issued_at = now` and mark the refresh as fired.
///
///    Build the candidate plaintext from `(effective_issued_at,
///    serde_json::to_vec(&payload))` and hash it. Emit when any of the
///    following holds: `state.needs_rewrite` is true (rotation migration or
///    expired-cookie cleanup forced upstream), the refresh fired, or the
///    candidate hash differs from `state.original_plaintext_hash`. Otherwise
///    skip the emission — the hash-compare suppresses no-op rewrites that
///    would otherwise fire on benign handler activity (read-only access,
///    `insert(same_value)`, `modify` no-op closures).
///
/// # Errors
///
/// `serde_json::to_vec(payload)` failure (which is exceptionally rare for
/// well-typed `T`) is treated as [`RewriteAction::None`] — the safe default.
/// A partial rewrite is worse than no rewrite; if the payload truly cannot
/// serialize, the next request will produce the same outcome and the
/// handler can react then.
///
/// # Time
///
/// `now` is supplied by the caller. This function performs no wall-clock
/// reads; it is fully deterministic given its inputs. The strict-`<` /
/// strict-`>` comparisons against `max_age` and `threshold` mean that at
/// exactly the boundary, the session is still valid (consistent with
/// [`SessionState::from_decrypt`]) and refresh does not fire (a session
/// exactly at the threshold is "unchanged enough" to skip the rewrite).
pub(crate) fn should_rewrite<T>(
    state: &SessionState<T>,
    max_age: Duration,
    refresh_after: Option<Duration>,
    now: SystemTime,
) -> RewriteAction
where
    T: Serialize,
{
    // Cases 1 and 2: no payload to emit. Distinguish by whether a prior
    // cookie was present so we know whether to clear the browser's copy.
    let Some(payload) = state.payload.as_ref() else {
        return if state.original_plaintext_hash.is_some() {
            RewriteAction::Delete
        } else {
            RewriteAction::None
        };
    };

    // Serialization failure is exceptionally rare for well-typed `T`; the
    // safe default is to emit nothing rather than risk a partial rewrite.
    let Ok(payload_json) = serde_json::to_vec(payload) else {
        return RewriteAction::None;
    };

    // A new session (no prior cookie) takes its `issued_at` from the response
    // path's `now`. A continuing session preserves the timestamp embedded in
    // the incoming cookie so a rotation-only rewrite cannot extend lifetime.
    let base_issued_at = if state.original_plaintext_hash.is_none() {
        now
    } else {
        state.issued_at
    };

    let mut effective_issued_at = base_issued_at;
    let mut refresh_fired = false;
    if let Some(threshold) = refresh_after
        && let Ok(age) = now.duration_since(base_issued_at)
        && age > threshold
        && age < max_age
    {
        effective_issued_at = now;
        refresh_fired = true;
    }

    let candidate = envelope::encode_envelope(effective_issued_at, &payload_json);
    let candidate_hash = sha256(&candidate);

    // For a brand-new session there is nothing to compare against, so we
    // always emit. For a continuing session we compare the candidate against
    // the cookie's original hash to suppress no-op rewrites.
    let hash_changed = match state.original_plaintext_hash {
        Some(h) => h != candidate_hash,
        None => true,
    };

    if state.needs_rewrite || refresh_fired || hash_changed {
        RewriteAction::Emit {
            plaintext: candidate,
            issued_at: effective_issued_at,
        }
    } else {
        RewriteAction::None
    }
}

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

    #[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)]
    struct UserPayload {
        id: u64,
        name: String,
    }

    fn fixed_time(secs: u64) -> SystemTime {
        SystemTime::UNIX_EPOCH + Duration::from_secs(secs)
    }

    /// Build a `DecodedCookie` whose `plaintext_hash` is a real SHA-256 of
    /// the layer-1 plaintext bytes, so tests that compare hashes exercise
    /// the production hashing path.
    fn decoded(
        payload: UserPayload,
        issued_secs: u64,
        key_idx: usize,
    ) -> DecodedCookie<UserPayload> {
        let payload_json = serde_json::to_vec(&payload).expect("UserPayload serializes cleanly");
        let layer1 = envelope::encode_envelope(fixed_time(issued_secs), &payload_json);
        DecodedCookie {
            payload,
            issued_at: fixed_time(issued_secs),
            plaintext_hash: sha256(&layer1),
            decrypt_key_index: key_idx,
        }
    }

    fn sample_payload() -> UserPayload {
        UserPayload {
            id: 42,
            name: "alice".into(),
        }
    }

    const DAY: Duration = Duration::from_secs(24 * 3_600);

    // --- new_empty -----------------------------------------------------------

    /// `new_empty` produces a state in the "no session" configuration: no
    /// payload, no prior hash, no decrypt index, neither flag set.
    #[test]
    fn new_empty_has_all_fields_in_no_session_configuration() {
        let now = fixed_time(1_000_000);
        let state: SessionState<UserPayload> = SessionState::new_empty(now);

        assert!(state.payload.is_none());
        assert_eq!(state.issued_at, now);
        assert!(state.original_plaintext_hash.is_none());
        assert!(state.decrypt_key_index.is_none());
        assert!(!state.mutated);
        assert!(!state.needs_rewrite);
    }

    // --- from_decrypt: no cookie --------------------------------------------

    /// `from_decrypt(None, _, now)` returns the same shape as `new_empty(now)`.
    /// No cookie on entry → no session on exit, with the decision-function
    /// "no rewrite" markers cleared.
    #[test]
    fn from_decrypt_no_cookie_produces_empty_state() {
        let now = fixed_time(1_000_000);
        let state: SessionState<UserPayload> = SessionState::from_decrypt(None, DAY, now);

        assert!(state.payload.is_none());
        assert_eq!(state.issued_at, now);
        assert!(state.original_plaintext_hash.is_none());
        assert!(state.decrypt_key_index.is_none());
        assert!(!state.mutated);
        assert!(!state.needs_rewrite);
    }

    // --- from_decrypt: valid cookie -----------------------------------------

    /// A non-expired cookie decrypted under the primary key (`index = 0`)
    /// preserves the payload and `issued_at`, records the plaintext hash
    /// and key index, and leaves `needs_rewrite = false` — there is nothing
    /// for the response path to emit unless the handler mutates.
    #[test]
    fn from_decrypt_valid_cookie_preserves_payload_and_issued_at() {
        let now = fixed_time(1_000_000);
        let issued_secs = 1_000_000 - 3_600; // now - 1h
        let payload = sample_payload();
        let d = decoded(payload.clone(), issued_secs, 0);
        let expected_hash = d.plaintext_hash;

        let state = SessionState::from_decrypt(Some(d), DAY, now);

        assert_eq!(state.payload, Some(payload));
        assert_eq!(state.issued_at, fixed_time(issued_secs));
        assert_eq!(state.original_plaintext_hash, Some(expected_hash));
        assert_eq!(state.decrypt_key_index, Some(0));
        assert!(!state.mutated);
        assert!(!state.needs_rewrite);
    }

    // --- from_decrypt: rotation flag (AC4.3) --------------------------------

    /// seshcookie-rs.AC4.3 (state-machine portion): when the cookie was
    /// decrypted under a non-primary fallback key (`index != 0`),
    /// `from_decrypt` flips `needs_rewrite = true` so the response path can
    /// auto-migrate to the primary. Both index 1 and index 2 must trigger.
    #[test]
    fn from_decrypt_fallback_key_sets_needs_rewrite_seshcookie_rs_ac4_3() {
        let now = fixed_time(1_000_000);
        let issued_secs = 1_000_000 - 3_600; // now - 1h
        let payload = sample_payload();

        for idx in [1usize, 2] {
            let d = decoded(payload.clone(), issued_secs, idx);
            let state = SessionState::from_decrypt(Some(d), DAY, now);

            assert_eq!(
                state.payload,
                Some(payload.clone()),
                "fallback decrypt must still surface the payload (idx {idx})"
            );
            assert_eq!(
                state.decrypt_key_index,
                Some(idx),
                "fallback index must be recorded (idx {idx})"
            );
            assert!(
                state.needs_rewrite,
                "non-primary index {idx} must set needs_rewrite"
            );
            assert!(
                !state.mutated,
                "from_decrypt must not pre-set the handler-mutation flag"
            );
        }
    }

    // --- from_decrypt: expiry (AC2.2) ---------------------------------------

    /// seshcookie-rs.AC2.2 (state-machine portion): a cookie whose
    /// `issued_at` is older than `now - max_age` is rejected. The state
    /// surfaces no payload, but it does record the original plaintext hash
    /// so the response path knows a cookie was present and can emit a
    /// delete. `needs_rewrite` is forced on for the same reason.
    #[test]
    fn from_decrypt_expired_cookie_sets_delete_markers_seshcookie_rs_ac2_2() {
        let now = fixed_time(1_000_000);
        // 25h old, max_age = 24h → strictly expired.
        let issued_secs = 1_000_000 - 25 * 3_600;
        let d = decoded(sample_payload(), issued_secs, 0);
        let expected_hash = d.plaintext_hash;
        let expected_idx = d.decrypt_key_index;

        let state = SessionState::from_decrypt(Some(d), DAY, now);

        assert!(
            state.payload.is_none(),
            "expired cookie must not surface payload"
        );
        assert_eq!(
            state.original_plaintext_hash,
            Some(expected_hash),
            "expired cookie must record original hash for the delete path"
        );
        assert_eq!(
            state.decrypt_key_index,
            Some(expected_idx),
            "expired cookie must record the index that decrypted it"
        );
        assert!(
            state.needs_rewrite,
            "expired cookie must force a rewrite (delete emission)"
        );
    }

    /// Boundary condition: a cookie at exactly `now - max_age` is *not*
    /// expired. The check uses `now > issued_at + max_age` (strict greater
    /// than), so equality is still valid — consistent with the design plan's
    /// "valid through T + max_age" wording.
    #[test]
    fn from_decrypt_at_expiry_boundary_not_expired() {
        let now = fixed_time(1_000_000);
        // Exactly max_age old — boundary is inclusive.
        let issued_secs = 1_000_000 - 24 * 3_600;
        let payload = sample_payload();
        let d = decoded(payload.clone(), issued_secs, 0);

        let state = SessionState::from_decrypt(Some(d), DAY, now);

        assert_eq!(state.payload, Some(payload));
        assert!(!state.needs_rewrite);
    }

    /// seshcookie-rs.AC2.2 (state-machine portion): one second past the
    /// boundary tips the cookie into the expired branch.
    #[test]
    fn from_decrypt_one_second_past_expiry_is_expired_seshcookie_rs_ac2_2() {
        let now = fixed_time(1_000_000);
        // max_age + 1s old → strictly expired.
        let issued_secs = 1_000_000 - (24 * 3_600 + 1);
        let d = decoded(sample_payload(), issued_secs, 0);

        let state = SessionState::from_decrypt(Some(d), DAY, now);

        assert!(state.payload.is_none());
        assert!(state.needs_rewrite);
    }

    /// `Duration::MAX` saturates `SystemTime::checked_add` for any non-epoch
    /// `issued_at`. The implementation falls back to "not expired" rather
    /// than panicking, so a configuration with an absurdly large `max_age`
    /// behaves as "effectively no expiry" instead of bricking every session.
    #[test]
    fn from_decrypt_overflow_treated_as_non_expired() {
        let now = fixed_time(1_000_000);
        let issued_secs = 1; // anywhere finite
        let payload = sample_payload();
        let d = decoded(payload.clone(), issued_secs, 0);

        let state = SessionState::from_decrypt(Some(d), Duration::MAX, now);

        assert_eq!(state.payload, Some(payload));
        assert!(!state.needs_rewrite);
    }

    // --- sha256 helper -------------------------------------------------------

    /// Spot-check the helper against the canonical NIST SHA-256 test vector
    /// for the input "abc". This pins the hashing behavior we rely on for
    /// the `original_plaintext_hash` field.
    #[test]
    fn sha256_matches_known_test_vector() {
        let expected: [u8; 32] = [
            0xba, 0x78, 0x16, 0xbf, 0x8f, 0x01, 0xcf, 0xea, 0x41, 0x41, 0x40, 0xde, 0x5d, 0xae,
            0x22, 0x23, 0xb0, 0x03, 0x61, 0xa3, 0x96, 0x17, 0x7a, 0x9c, 0xb4, 0x10, 0xff, 0x61,
            0xf2, 0x00, 0x15, 0xad,
        ];
        assert_eq!(sha256(b"abc"), expected);
    }

    /// `SessionState` must implement `Debug` even when its payload type does
    /// not. The output never embeds the payload bytes — only the redaction
    /// marker — so trace logs cannot leak session contents.
    #[test]
    fn session_state_debug_redacts_payload_and_does_not_require_t_debug() {
        // A type explicitly without `Debug`. If the redaction path leaked the
        // payload through `T: Debug`, this test would not compile.
        struct NoDebugPayload(#[allow(dead_code)] u32);

        let now = fixed_time(1_000_000);
        let state: SessionState<NoDebugPayload> = SessionState {
            payload: Some(NoDebugPayload(7)),
            issued_at: now,
            original_plaintext_hash: Some([0u8; 32]),
            decrypt_key_index: Some(0),
            mutated: true,
            needs_rewrite: false,
        };

        let s = format!("{state:?}");
        assert!(
            s.contains("<redacted>"),
            "Debug output should redact payload bytes: {s}"
        );
        assert!(
            !s.contains('7'),
            "payload value must not appear in Debug output: {s}"
        );
    }

    /// `DecodedCookie` similarly redacts its payload from `Debug` output.
    #[test]
    fn decoded_cookie_debug_redacts_payload() {
        struct NoDebugPayload(#[allow(dead_code)] u32);

        let cookie = DecodedCookie {
            payload: NoDebugPayload(99),
            issued_at: fixed_time(1_000_000),
            plaintext_hash: [0u8; 32],
            decrypt_key_index: 1,
        };

        let s = format!("{cookie:?}");
        assert!(
            s.contains("<redacted>"),
            "Debug output should redact payload: {s}"
        );
        assert!(
            !s.contains("99"),
            "payload value must not appear in Debug output: {s}"
        );
    }

    // --- should_rewrite: decision-table coverage --------------------------------

    /// Construct a `SessionState` whose `original_plaintext_hash` is the real
    /// SHA-256 of the layer-1 plaintext for the given payload and `issued_at`.
    /// Lets the `should_rewrite` tests build a "just decoded the cookie" state
    /// without going through the (yet to exist) Phase 3 request path.
    fn state_from_valid_cookie(
        payload: UserPayload,
        issued_secs: u64,
        key_idx: usize,
        max_age: Duration,
        now: SystemTime,
    ) -> SessionState<UserPayload> {
        SessionState::from_decrypt(Some(decoded(payload, issued_secs, key_idx)), max_age, now)
    }

    const HOUR: Duration = Duration::from_secs(3_600);

    /// Decode an emitted layer-1 plaintext back into `(issued_at, payload)`.
    /// Used by the should_rewrite tests to assert that emitted bytes round-
    /// trip to the expected payload and timestamp.
    fn decode_emitted(plaintext: &[u8]) -> (SystemTime, UserPayload) {
        let (ts, payload_bytes) =
            envelope::decode_envelope(plaintext).expect("emitted plaintext must decode");
        let payload: UserPayload = serde_json::from_slice(&payload_bytes)
            .expect("payload bytes must parse as UserPayload");
        (ts, payload)
    }

    /// Decision table row 1 (payload=None + hash=Some): a read-only handler
    /// against a valid cookie emits zero `Set-Cookie` headers.
    /// (Already covered above as the initial TDD RED test —
    /// `should_rewrite_read_only_emits_none_seshcookie_rs_ac3_1`.)
    ///
    /// seshcookie-rs.AC3.1: `session.get().await` followed by no mutation. The
    /// candidate plaintext hash matches `original_plaintext_hash`, no rotation
    /// migration is pending, no refresh fires, so the response path emits
    /// nothing.
    #[test]
    fn should_rewrite_read_only_emits_none_seshcookie_rs_ac3_1() {
        let now = fixed_time(1_000_000);
        let issued_secs = 1_000_000 - 3_600;
        let state = state_from_valid_cookie(sample_payload(), issued_secs, 0, DAY, now);

        let action = should_rewrite(&state, DAY, None, now);

        assert!(
            matches!(action, RewriteAction::None),
            "read-only handler must not trigger a Set-Cookie: got {action:?}"
        );
    }

    /// seshcookie-rs.AC3.2: `session.insert(same_value)` is suppressed by the
    /// hash-compare. `state.mutated = true` alone does not force a rewrite —
    /// the candidate plaintext must hash equal to the original. This is decision
    /// table row 4 (payload=Some + mutated + hash same → None).
    #[test]
    fn should_rewrite_insert_same_value_suppressed_by_hash_seshcookie_rs_ac3_2() {
        let now = fixed_time(1_000_000);
        let issued_secs = 1_000_000 - 3_600;
        let mut state = state_from_valid_cookie(sample_payload(), issued_secs, 0, DAY, now);

        // Simulate `Session::insert(same_value)`: payload identical, mutated flag set.
        state.mutated = true;

        let action = should_rewrite(&state, DAY, None, now);

        assert!(
            matches!(action, RewriteAction::None),
            "insert(same_value) must be suppressed by hash-compare: got {action:?}"
        );
    }

    /// seshcookie-rs.AC3.3: `session.insert(different_value)` emits exactly one
    /// `Set-Cookie` whose plaintext encodes the new payload at the
    /// **preserved** `issued_at` (no refresh triggered).
    /// Decision table row 3 (payload=Some + mutated + hash differs → Emit,
    /// issued_at preserved).
    #[test]
    fn should_rewrite_insert_different_value_emits_seshcookie_rs_ac3_3() {
        let now = fixed_time(1_000_000);
        let issued_secs = 1_000_000 - 3_600;
        let original_issued_at = fixed_time(issued_secs);
        let mut state = state_from_valid_cookie(sample_payload(), issued_secs, 0, DAY, now);

        // Simulate `Session::insert(different_value)`.
        let new_payload = UserPayload {
            id: 100,
            name: "bob".into(),
        };
        state.payload = Some(new_payload.clone());
        state.mutated = true;

        let action = should_rewrite(&state, DAY, None, now);

        match action {
            RewriteAction::Emit {
                plaintext,
                issued_at,
            } => {
                assert_eq!(
                    issued_at, original_issued_at,
                    "data-change rewrite must preserve original issued_at"
                );
                let (decoded_ts, decoded_payload) = decode_emitted(&plaintext);
                assert_eq!(decoded_ts, original_issued_at);
                assert_eq!(decoded_payload, new_payload);
            }
            other => panic!("expected Emit, got {other:?}"),
        }
    }

    /// seshcookie-rs.AC3.4: `session.modify(|_|()).await` (no-op closure) is
    /// suppressed by the hash-compare even though `mutated = true`. Same
    /// decision-table row as AC3.2 (row 4), but a separate test makes the
    /// AC reference explicit.
    #[test]
    fn should_rewrite_modify_no_op_suppressed_by_hash_seshcookie_rs_ac3_4() {
        let now = fixed_time(1_000_000);
        let issued_secs = 1_000_000 - 3_600;
        let mut state = state_from_valid_cookie(sample_payload(), issued_secs, 0, DAY, now);

        // Simulate `Session::modify(|_|())`: handler ran, no fields touched.
        state.mutated = true;

        let action = should_rewrite(&state, DAY, None, now);

        assert!(
            matches!(action, RewriteAction::None),
            "modify(no-op) must be suppressed by hash-compare: got {action:?}"
        );
    }

    /// seshcookie-rs.AC3.5: `session.clear()` on a request with a valid cookie
    /// emits exactly one delete cookie. Decision table row 1 (payload=None +
    /// hash=Some → Delete).
    #[test]
    fn should_rewrite_clear_on_valid_cookie_returns_delete_seshcookie_rs_ac3_5() {
        let now = fixed_time(1_000_000);
        let issued_secs = 1_000_000 - 3_600;
        let mut state = state_from_valid_cookie(sample_payload(), issued_secs, 0, DAY, now);

        // Simulate `Session::clear()` on a request that had a cookie.
        state.payload = None;
        state.mutated = true;

        let action = should_rewrite(&state, DAY, None, now);

        assert!(
            matches!(action, RewriteAction::Delete),
            "clear() on valid cookie must request delete: got {action:?}"
        );
    }

    /// seshcookie-rs.AC3.6: `session.clear()` on a request without a cookie
    /// emits nothing. Decision table row 2 (payload=None + hash=None → None).
    #[test]
    fn should_rewrite_clear_on_no_cookie_returns_none_seshcookie_rs_ac3_6() {
        let now = fixed_time(1_000_000);
        let mut state: SessionState<UserPayload> = SessionState::from_decrypt(None, DAY, now);

        // Simulate `Session::clear()` when there was no incoming cookie.
        state.mutated = true;

        let action = should_rewrite(&state, DAY, None, now);

        assert!(
            matches!(action, RewriteAction::None),
            "clear() with no incoming cookie must not emit anything: got {action:?}"
        );
    }

    /// seshcookie-rs.AC4.3 + seshcookie-rs.AC4.4: a cookie decrypted under a
    /// fallback key (`needs_rewrite = true`, payload unchanged) emits exactly
    /// one `Set-Cookie` carrying the original `issued_at`. Decision table row
    /// 5 (payload=Some + needs_rewrite + hash same → Emit, issued_at preserved).
    /// Rotation alone must not extend session lifetime.
    #[test]
    fn should_rewrite_rotation_emits_with_preserved_issued_at_seshcookie_rs_ac4_3_ac4_4() {
        let now = fixed_time(1_000_000);
        let issued_secs = 1_000_000 - 3_600;
        let original_issued_at = fixed_time(issued_secs);
        let payload = sample_payload();
        let state = state_from_valid_cookie(payload.clone(), issued_secs, 2, DAY, now);
        assert!(
            state.needs_rewrite,
            "from_decrypt must set needs_rewrite for non-primary key index"
        );

        let action = should_rewrite(&state, DAY, None, now);

        match action {
            RewriteAction::Emit {
                plaintext,
                issued_at,
            } => {
                assert_eq!(
                    issued_at, original_issued_at,
                    "rotation-only rewrite must preserve issued_at (AC4.4)"
                );
                let (decoded_ts, decoded_payload) = decode_emitted(&plaintext);
                assert_eq!(decoded_ts, original_issued_at);
                assert_eq!(decoded_payload, payload);
            }
            other => panic!("expected Emit, got {other:?}"),
        }
    }

    /// seshcookie-rs.AC8.1: with `refresh_after = None` (default), a 23h-old
    /// session under a 24h `max_age` reads with no emission. The refresh
    /// branch is gated on `Some(threshold)`, so passing `None` skips it
    /// entirely; the read-only AC3.1 path takes over.
    #[test]
    fn should_rewrite_refresh_none_no_emission_at_23h_seshcookie_rs_ac8_1() {
        let now = fixed_time(1_000_000);
        let issued_secs = 1_000_000 - 23 * 3_600;
        let state = state_from_valid_cookie(sample_payload(), issued_secs, 0, DAY, now);

        let action = should_rewrite(&state, DAY, None, now);

        assert!(
            matches!(action, RewriteAction::None),
            "refresh_after=None must never trigger a refresh rewrite: got {action:?}"
        );
    }

    /// seshcookie-rs.AC8.2: with `refresh_after = Some(1h)` and a 30-minute-old
    /// session, the age is below the refresh threshold so no rewrite fires.
    /// This is the "within window" half of the sliding-refresh contract.
    #[test]
    fn should_rewrite_refresh_within_window_no_emission_seshcookie_rs_ac8_2() {
        let now = fixed_time(1_000_000);
        let issued_secs = 1_000_000 - 30 * 60; // 30 minutes ago
        let state = state_from_valid_cookie(sample_payload(), issued_secs, 0, DAY, now);

        let action = should_rewrite(&state, DAY, Some(HOUR), now);

        assert!(
            matches!(action, RewriteAction::None),
            "age below refresh threshold must not emit: got {action:?}"
        );
    }

    /// seshcookie-rs.AC8.3: with `refresh_after = Some(1h)`, `max_age = 24h`,
    /// and a 2h-old session, the threshold is exceeded but the session has
    /// not expired. Decision table row 6 (payload=Some + refresh fires →
    /// Emit, issued_at bumped). The emitted plaintext must encode the bumped
    /// `issued_at = now` and the unchanged payload.
    #[test]
    fn should_rewrite_refresh_threshold_exceeded_emits_bumped_issued_at_seshcookie_rs_ac8_3() {
        let now = fixed_time(1_000_000);
        let issued_secs = 1_000_000 - 2 * 3_600; // 2h ago
        let payload = sample_payload();
        let state = state_from_valid_cookie(payload.clone(), issued_secs, 0, DAY, now);

        let action = should_rewrite(&state, DAY, Some(HOUR), now);

        match action {
            RewriteAction::Emit {
                plaintext,
                issued_at,
            } => {
                assert_eq!(
                    issued_at, now,
                    "refresh-fired rewrite must bump issued_at to now"
                );
                let (decoded_ts, decoded_payload) = decode_emitted(&plaintext);
                assert_eq!(decoded_ts, now);
                assert_eq!(decoded_payload, payload);
            }
            other => panic!("expected Emit, got {other:?}"),
        }
    }

    /// seshcookie-rs.AC8.4: simultaneous refresh-triggered rewrite + rotation
    /// migration produces a single emission whose `issued_at` is bumped to
    /// `now`. Decision table row 7 (payload=Some + refresh + rotation → Emit,
    /// issued_at bumped). Phase 3 will re-encrypt under the primary key on
    /// emit, completing both effects in one `Set-Cookie`.
    #[test]
    fn should_rewrite_refresh_plus_rotation_emits_bumped_issued_at_seshcookie_rs_ac8_4() {
        let now = fixed_time(1_000_000);
        let issued_secs = 1_000_000 - 2 * 3_600; // 2h ago — past refresh threshold
        let payload = sample_payload();
        // key_idx = 1 forces `needs_rewrite = true` via the rotation branch.
        let state = state_from_valid_cookie(payload.clone(), issued_secs, 1, DAY, now);
        assert!(
            state.needs_rewrite,
            "rotation-key cookie must already carry needs_rewrite"
        );

        let action = should_rewrite(&state, DAY, Some(HOUR), now);

        match action {
            RewriteAction::Emit {
                plaintext,
                issued_at,
            } => {
                assert_eq!(
                    issued_at, now,
                    "simultaneous refresh+rotation must use bumped issued_at"
                );
                let (decoded_ts, decoded_payload) = decode_emitted(&plaintext);
                assert_eq!(decoded_ts, now);
                assert_eq!(decoded_payload, payload);
            }
            other => panic!("expected Emit, got {other:?}"),
        }
    }

    /// seshcookie-rs.AC8.5: a 25h-old session under `max_age = 24h` is
    /// rejected as expired even when `refresh_after = Some(1h)` is set. The
    /// expired branch of `from_decrypt` strips `payload`, so `should_rewrite`
    /// runs the Delete branch (decision table row 1) — refresh never gets a
    /// chance to fire.
    #[test]
    fn should_rewrite_25h_old_with_refresh_returns_delete_seshcookie_rs_ac8_5() {
        let now = fixed_time(1_000_000);
        let issued_secs = 1_000_000 - 25 * 3_600;
        let state = state_from_valid_cookie(sample_payload(), issued_secs, 0, DAY, now);

        // Sanity: from_decrypt should already have parked us at the expired
        // shape, ahead of the should_rewrite call.
        assert!(state.payload.is_none(), "expired cookie must drop payload");
        assert!(
            state.original_plaintext_hash.is_some(),
            "expired cookie must record hash for the delete path"
        );

        let action = should_rewrite(&state, DAY, Some(HOUR), now);

        assert!(
            matches!(action, RewriteAction::Delete),
            "expired session must return Delete regardless of refresh policy: got {action:?}"
        );
    }

    /// Decision table row 8 (payload=Some, no prior cookie, handler called
    /// `insert`): a brand-new session emits exactly one `Set-Cookie` whose
    /// `issued_at = now`. The candidate plaintext must encode `now` and the
    /// payload bytes.
    #[test]
    fn should_rewrite_new_session_from_insert_emits_with_now_issued_at() {
        let now = fixed_time(1_000_000);
        let mut state: SessionState<UserPayload> = SessionState::from_decrypt(None, DAY, now);

        // Simulate `Session::insert(payload)` on a request without a cookie.
        let payload = sample_payload();
        state.payload = Some(payload.clone());
        state.mutated = true;

        let action = should_rewrite(&state, DAY, None, now);

        match action {
            RewriteAction::Emit {
                plaintext,
                issued_at,
            } => {
                assert_eq!(issued_at, now, "new session must use now as issued_at");
                let (decoded_ts, decoded_payload) = decode_emitted(&plaintext);
                assert_eq!(decoded_ts, now);
                assert_eq!(decoded_payload, payload);
            }
            other => panic!("expected Emit, got {other:?}"),
        }
    }

    // --- should_rewrite: edge cases for branch coverage -------------------------

    /// Refresh threshold equality: at exactly `age == threshold`, the refresh
    /// branch's strict `age > threshold` does not fire. Pins the boundary
    /// behavior described in the implementation notes.
    #[test]
    fn should_rewrite_refresh_at_exact_threshold_does_not_fire() {
        let now = fixed_time(1_000_000);
        let issued_secs = 1_000_000 - 3_600; // exactly 1h ago
        let state = state_from_valid_cookie(sample_payload(), issued_secs, 0, DAY, now);

        let action = should_rewrite(&state, DAY, Some(HOUR), now);

        assert!(
            matches!(action, RewriteAction::None),
            "age == threshold must not fire refresh: got {action:?}"
        );
    }

    /// Refresh + max_age equality: at exactly `age == max_age`, the strict
    /// `age < max_age` blocks refresh and `from_decrypt`'s strict `now >
    /// expiry` keeps the session valid. Net result: no emission.
    #[test]
    fn should_rewrite_refresh_at_exact_max_age_does_not_fire() {
        let now = fixed_time(1_000_000);
        let issued_secs = 1_000_000 - 24 * 3_600;
        let state = state_from_valid_cookie(sample_payload(), issued_secs, 0, DAY, now);

        // The session is still valid at the boundary (from_decrypt allows it),
        // but refresh is gated on `age < max_age` strictly.
        assert!(state.payload.is_some());

        let action = should_rewrite(&state, DAY, Some(HOUR), now);

        assert!(
            matches!(action, RewriteAction::None),
            "age == max_age must not fire refresh: got {action:?}"
        );
    }

    /// `now` earlier than the cookie's `issued_at` means
    /// `now.duration_since(issued_at)` returns `Err`. The refresh branch
    /// silently skips, leaving only the hash-compare suppression to act.
    /// This guards against negative-age sessions emitted by clock skew or a
    /// fixture that mistakenly puts `issued_at` in the future.
    #[test]
    fn should_rewrite_now_before_issued_at_skips_refresh() {
        let now = fixed_time(1_000_000);
        // Cookie issued in the future relative to `now`.
        let issued_secs = 1_000_000 + 3_600;
        let state = state_from_valid_cookie(sample_payload(), issued_secs, 0, DAY, now);

        let action = should_rewrite(&state, DAY, Some(HOUR), now);

        assert!(
            matches!(action, RewriteAction::None),
            "now < issued_at must skip refresh and not emit: got {action:?}"
        );
    }
}