rmcp 3.2.0

Rust SDK for Model Context Protocol
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
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
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
//! Integrity protection for SEP-2322 `requestState`.
//!
//! In the multi round-trip request (MRTR) flow, a server places an opaque
//! `requestState` string in an [`InputRequiredResult`](super::InputRequiredResult)
//! and the client echoes it back verbatim on retry. From the server's point of
//! view the echoed value is **untrusted, attacker-controlled input**: a client
//! can send back anything it likes. Per SEP-2322, a server that lets
//! `requestState` influence authorization, resource access, or business logic
//! MUST protect its integrity and reject values that fail verification.
//!
//! [`RequestStateCodec`] provides an opt-in way to do this. It seals a payload
//! into an opaque string with an HMAC-SHA256 tag and opens it again, rejecting
//! any value that was forged or tampered with.
//!
//! To follow the spec's replay-prevention guidance without hand-rolling the
//! checks, the codec supports two bindings via [`SealOptions`]:
//!
//! * **Associated data** — arbitrary context (e.g. the authenticated principal
//!   plus a digest of the originating request) that is mixed into the tag but
//!   not stored in the token. [`open_with`](RequestStateCodec::open_with) only
//!   succeeds when the caller supplies the same context, so a value cannot be
//!   replayed by a different principal or against a different request. This is
//!   *fail-closed*: forgetting to pass the context makes verification fail.
//! * **TTL** — a relative expiry stamped into the token; opening a value past
//!   its expiry fails with [`RequestStateError::Expired`].
//!
//! Single-use/nonce enforcement (for one-time redemptions) still has to be done
//! server-side, as the spec notes.
//!
//! This helper is only about *integrity*, not *confidentiality*: the sealed
//! payload is signed, not encrypted, so it is base64url-readable by anyone. Do
//! not put secrets in it.
//!
//! Using the codec is entirely optional. A server that keeps its state
//! server-side, or that does not trust `requestState` for anything security
//! sensitive, can keep building the string by hand via
//! [`InputRequiredResult::from_request_state`](super::InputRequiredResult::from_request_state).
//!
//! # Examples
//!
//! ```
//! use rmcp::model::{RequestStateCodec, SealOptions};
//! # fn main() -> Result<(), rmcp::model::RequestStateError> {
//!
//! // Derive the key from a per-process secret; keep it out of client reach.
//! let codec = RequestStateCodec::try_new(b"a-32-byte-or-longer-secret-key!!!")?;
//!
//! // Bind the state to the caller and the originating request.
//! let context = b"user:alice|tools/call:weather";
//! let sealed = codec.seal_with(
//!     b"step=2",
//!     &SealOptions::new().associated_data(context),
//! );
//!
//! // On retry the client echoes `sealed` back untouched; the server re-derives
//! // the same context and opens it.
//! let opened = codec.open_with(&sealed, context)?;
//! assert_eq!(opened, b"step=2");
//!
//! // A different principal (different context) is rejected.
//! assert!(codec.open_with(&sealed, b"user:bob|tools/call:weather").is_err());
//! # Ok(())
//! # }
//! ```

use std::{
    collections::{HashMap, hash_map::Entry},
    time::Duration,
};

use base64::{Engine, engine::general_purpose::URL_SAFE_NO_PAD};
use hmac::{Hmac, KeyInit, Mac};
use serde::{Serialize, de::DeserializeOwned};
use sha2::Sha256;
use thiserror::Error;
use zeroize::Zeroizing;

type HmacSha256 = Hmac<Sha256>;

const VERSION_V1: &str = "rs1";

const VERSION_V2: &str = "rs2";

/// Domain-separation label mixed into the HMAC so a `requestState` tag can never
/// be confused with an HMAC computed for some other purpose using the same key.
const DOMAIN_V1: &[u8] = b"rmcp/mrtr/request-state/v1";

/// Domain-separation label for keyed request-state tags.
const DOMAIN_V2: &[u8] = b"rmcp/mrtr/request-state/v2";

/// Length of the big-endian expiry prefix (unix milliseconds) stored at the
/// front of every sealed body. `0` means "no expiry".
const EXPIRY_LEN: usize = 8;

const MAX_KID_LEN: usize = 255;

/// Maximum unpadded base64url length for [`MAX_KID_LEN`] bytes.
const MAX_ENCODED_KID_LEN: usize = 340;

/// Errors returned when constructing or configuring a
/// [`RequestStateCodec`], or when processing a sealed value.
#[derive(Debug, Error)]
#[non_exhaustive]
pub enum RequestStateError {
    /// The signing key is shorter than [`RequestStateCodec::MIN_KEY_LENGTH`].
    #[error(
        "request state signing key is too short: expected at least {minimum} bytes, got {actual}"
    )]
    KeyTooShort { minimum: usize, actual: usize },

    /// The value is not a well-formed sealed request state (wrong prefix or
    /// missing sections).
    #[error("request state is malformed or uses an unsupported format")]
    MalformedFormat,

    /// A section of the value was not valid base64url.
    #[error("request state is not valid base64url")]
    InvalidEncoding,

    /// The HMAC tag did not match; the value was forged, tampered with, or
    /// opened with the wrong associated data.
    #[error("request state failed integrity verification")]
    IntegrityCheckFailed,

    /// The value carried a TTL that has already elapsed.
    #[error("request state has expired")]
    Expired,

    /// The token names (or, for rs1, requires) a key this codec does not hold.
    #[error("request state was sealed with an unknown key")]
    UnknownKeyId,

    /// The decoded rs2 key id was empty, too long, or not valid UTF-8.
    #[error("request state contains an invalid key identifier")]
    InvalidKeyId,

    /// An invalid keyring configuration; the message is diagnostic only.
    #[error("invalid keyring configuration: {0}")]
    InvalidKeyring(&'static str),

    /// The sealed payload could not be serialized to JSON.
    #[error("failed to serialize request state payload: {0}")]
    Serialization(#[source] serde_json::Error),

    /// The opened payload could not be deserialized from JSON.
    #[error("failed to deserialize request state payload: {0}")]
    Deserialization(#[source] serde_json::Error),
}

/// Options controlling how a value is sealed by [`RequestStateCodec`].
///
/// Defaults to no associated data and no expiry, which is equivalent to the
/// bare [`seal`](RequestStateCodec::seal) / [`open`](RequestStateCodec::open)
/// methods.
#[derive(Clone, Copy, Debug, Default)]
pub struct SealOptions<'a> {
    associated_data: &'a [u8],
    ttl: Option<Duration>,
}

impl<'a> SealOptions<'a> {
    /// Creates empty options (no associated data, no expiry).
    pub fn new() -> Self {
        Self::default()
    }

    /// Binds the sealed value to `associated_data`. The same bytes must be
    /// supplied to [`open_with`](RequestStateCodec::open_with); the data is
    /// authenticated but not stored in the token.
    ///
    /// Use this to bind the state to the authenticated principal and/or the
    /// originating request (e.g. method name plus a digest of its parameters).
    pub fn associated_data(mut self, associated_data: &'a [u8]) -> Self {
        self.associated_data = associated_data;
        self
    }

    /// Sets a relative time-to-live after which opening the value fails with
    /// [`RequestStateError::Expired`].
    pub fn ttl(mut self, ttl: Duration) -> Self {
        self.ttl = Some(ttl);
        self
    }
}

/// A keyed codec for integrity-protected SEP-2322 `requestState` values.
///
/// [`new`](Self::new) preserves `rs1`; [`new_with_keyring`](Self::new_with_keyring)
/// emits `rs2`.
/// Use [`with_rs1_signing`](Self::with_rs1_signing) and
/// [`with_rs1_fallback`](Self::with_rs1_fallback) for rolling migrations.
///
/// Use [`try_new`](Self::try_new) and
/// [`new_with_keyring`](Self::new_with_keyring) to require at least
/// [`MIN_KEY_LENGTH`](Self::MIN_KEY_LENGTH) bytes of high-entropy key material.
/// Configure the same keys on every replica. Stored key material is zeroized
/// when the codec is dropped.
///
/// Values are authenticated, not encrypted; key ids and payloads remain
/// readable. Retain old keys until every value they signed has expired.
///
/// # Key rotation
///
/// Rotate in stages so every replica can open states emitted by its peers:
///
/// ```
/// # use rmcp::model::{RequestStateCodec, RequestStateError};
/// # fn main() -> Result<(), RequestStateError> {
/// let old_key = b"old-request-state-key-at-least-32b".as_slice();
/// let new_key = b"new-request-state-key-at-least-32b".as_slice();
/// let keys = [("old", old_key), ("new", new_key)];
///
/// // 1. Deploy both keys, but continue emitting rs1 with the old key.
/// let transitional = RequestStateCodec::new_with_keyring("new", keys)?
///     .with_rs1_signing("old")?;
///
/// // 2. Emit rs2 with the new key, while accepting in-flight rs1 values.
/// let promoted = RequestStateCodec::new_with_keyring("new", keys)?
///     .with_rs1_fallback("old")?;
///
/// let old_state = transitional.seal(b"old state");
/// assert_eq!(promoted.open(&old_state)?, b"old state");
/// let new_state = promoted.seal(b"new state");
/// assert_eq!(transitional.open(&new_state)?, b"new state");
///
/// // 3. After old values expire, remove the old key.
/// let retired = RequestStateCodec::new_with_keyring("new", [("new", new_key)])?;
/// assert_eq!(retired.open(&new_state)?, b"new state");
/// # Ok(())
/// # }
/// ```
#[derive(Clone)]
pub struct RequestStateCodec {
    keys: Keys,
}

#[derive(Clone)]
enum Keys {
    Single(Zeroizing<Vec<u8>>),
    Ring {
        keys: HashMap<String, Zeroizing<Vec<u8>>>,
        seal_mode: SealMode,
        rs1_fallbacks: Vec<String>,
    },
}

#[derive(Clone, Debug)]
enum SealMode {
    Rs1 { key_id: String },
    Rs2 { key_id: String },
}

impl std::fmt::Debug for RequestStateCodec {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        // Never leak signing or verification keys through Debug output.
        match &self.keys {
            Keys::Single(_) => f
                .debug_struct("RequestStateCodec")
                .field("mode", &"single")
                .field("key", &"<redacted>")
                .finish(),
            Keys::Ring {
                keys,
                seal_mode,
                rs1_fallbacks,
            } => f
                .debug_struct("RequestStateCodec")
                .field("mode", &"ring")
                .field("key_count", &keys.len())
                .field("keys", &"<redacted>")
                .field("seal_mode", seal_mode)
                .field("rs1_fallbacks", rs1_fallbacks)
                .finish(),
        }
    }
}

impl RequestStateCodec {
    /// Minimum accepted signing-key length in bytes.
    pub const MIN_KEY_LENGTH: usize = 32;

    /// Creates a legacy single-key codec that seals and opens `rs1` values
    /// without validating the signing-key length.
    #[deprecated(
        since = "3.1.4",
        note = "use RequestStateCodec::try_new to enforce the minimum signing-key length"
    )]
    pub fn new(key: impl Into<Vec<u8>>) -> Self {
        Self::new_unchecked(key)
    }

    /// Creates a codec without validating the signing-key length.
    ///
    /// Prefer [`try_new`](Self::try_new) unless the key length has already been
    /// validated.
    pub fn new_unchecked(key: impl Into<Vec<u8>>) -> Self {
        Self {
            keys: Keys::Single(Zeroizing::new(key.into())),
        }
    }

    /// Creates a legacy single-key codec after validating its signing-key length.
    ///
    /// # Errors
    ///
    /// Returns [`RequestStateError::KeyTooShort`] when `key` contains fewer
    /// than [`MIN_KEY_LENGTH`](Self::MIN_KEY_LENGTH) bytes.
    pub fn try_new(key: impl Into<Vec<u8>>) -> Result<Self, RequestStateError> {
        let key = Zeroizing::new(key.into());
        Self::validate_key_length(&key)?;
        Ok(Self {
            keys: Keys::Single(key),
        })
    }

    /// Creates a keyring codec that seals `rs2` with `active_kid`.
    ///
    /// All configured keys can open matching `rs2` values. Legacy `rs1` values
    /// require [`with_rs1_fallback`](Self::with_rs1_fallback) or
    /// [`with_rs1_signing`](Self::with_rs1_signing).
    /// Key ids are case-sensitive UTF-8 strings of 1 to 255 bytes.
    ///
    /// # Errors
    ///
    /// Returns [`RequestStateError::KeyTooShort`] if a configured key contains
    /// fewer than [`MIN_KEY_LENGTH`](Self::MIN_KEY_LENGTH) bytes. Returns
    /// [`RequestStateError::InvalidKeyring`] if the keyring is empty, contains
    /// duplicate or invalid key ids, or does not contain `active_kid`.
    pub fn new_with_keyring<K, V>(
        active_kid: impl Into<String>,
        keys: impl IntoIterator<Item = (K, V)>,
    ) -> Result<Self, RequestStateError>
    where
        K: Into<String>,
        V: Into<Vec<u8>>,
    {
        let mut ring = HashMap::new();
        for (kid, key) in keys {
            let kid = kid.into();
            let key = Zeroizing::new(key.into());
            Self::validate_config_kid(&kid)?;
            Self::validate_key_length(&key)?;
            match ring.entry(kid) {
                Entry::Vacant(entry) => {
                    entry.insert(key);
                }
                Entry::Occupied(_) => {
                    return Err(RequestStateError::InvalidKeyring("duplicate key id"));
                }
            }
        }

        if ring.is_empty() {
            return Err(RequestStateError::InvalidKeyring(
                "keyring must contain at least one key",
            ));
        }

        let active_kid = active_kid.into();
        Self::validate_config_kid(&active_kid)?;
        if !ring.contains_key(&active_kid) {
            return Err(RequestStateError::InvalidKeyring(
                "active key id is not present in the keyring",
            ));
        }

        Ok(Self {
            keys: Keys::Ring {
                keys: ring,
                seal_mode: SealMode::Rs2 { key_id: active_kid },
                rs1_fallbacks: Vec::new(),
            },
        })
    }

    /// Uses `kid` to sign legacy `rs1` values during a rolling migration.
    /// The codec accepts its own `rs1` output and configured `rs2` values.
    ///
    /// # Errors
    ///
    /// Returns [`RequestStateError::InvalidKeyring`] when called on a single-key
    /// codec, or if the keyring does not contain `kid`.
    pub fn with_rs1_signing(mut self, kid: impl AsRef<str>) -> Result<Self, RequestStateError> {
        let kid = kid.as_ref();
        match &mut self.keys {
            Keys::Single(_) => Err(RequestStateError::InvalidKeyring(
                "rs1 transitional signing requires a keyring",
            )),
            Keys::Ring {
                keys,
                seal_mode,
                rs1_fallbacks,
            } => {
                if !keys.contains_key(kid) {
                    return Err(RequestStateError::InvalidKeyring(
                        "rs1 signing key id is not present in the keyring",
                    ));
                }

                let kid = kid.to_owned();
                *seal_mode = SealMode::Rs1 {
                    key_id: kid.clone(),
                };
                if !rs1_fallbacks.iter().any(|existing| existing == &kid) {
                    rs1_fallbacks.push(kid);
                }
                Ok(self)
            }
        }
    }

    /// Accepts legacy `rs1` values signed with `kid`.
    /// Adding the same id more than once has no effect; remove fallbacks after
    /// old values have drained.
    ///
    /// # Errors
    ///
    /// Returns [`RequestStateError::InvalidKeyring`] when called on a single-key
    /// codec, or if the keyring does not contain `kid`.
    pub fn with_rs1_fallback(mut self, kid: impl AsRef<str>) -> Result<Self, RequestStateError> {
        let kid = kid.as_ref();
        match &mut self.keys {
            Keys::Single(_) => Err(RequestStateError::InvalidKeyring(
                "rs1 fallbacks require a keyring",
            )),
            Keys::Ring {
                keys,
                rs1_fallbacks,
                ..
            } => {
                if !keys.contains_key(kid) {
                    return Err(RequestStateError::InvalidKeyring(
                        "rs1 fallback key id is not present in the keyring",
                    ));
                }
                if !rs1_fallbacks.iter().any(|existing| existing == kid) {
                    rs1_fallbacks.push(kid.to_owned());
                }
                Ok(self)
            }
        }
    }

    /// Seals raw bytes into an opaque, integrity-protected string suitable for
    /// use as `requestState`.
    pub fn seal(&self, payload: &[u8]) -> String {
        self.seal_with(payload, &SealOptions::default())
    }

    /// Seals raw bytes with [`SealOptions`] (associated data and/or TTL).
    pub fn seal_with(&self, payload: &[u8], options: &SealOptions<'_>) -> String {
        self.seal_at(payload, options, Self::now_ms())
    }

    /// Seals a serializable value by encoding it as JSON before sealing.
    ///
    /// # Errors
    ///
    /// Returns [`RequestStateError::Serialization`] if `value` cannot be encoded
    /// as JSON.
    pub fn seal_json<T: Serialize>(&self, value: &T) -> Result<String, RequestStateError> {
        self.seal_json_with(value, &SealOptions::default())
    }

    /// Seals a serializable value with [`SealOptions`].
    ///
    /// # Errors
    ///
    /// Returns [`RequestStateError::Serialization`] if `value` cannot be encoded
    /// as JSON.
    pub fn seal_json_with<T: Serialize>(
        &self,
        value: &T,
        options: &SealOptions<'_>,
    ) -> Result<String, RequestStateError> {
        let payload = serde_json::to_vec(value).map_err(RequestStateError::Serialization)?;
        Ok(self.seal_with(&payload, options))
    }

    /// Opens a sealed value that was sealed without associated data, verifying
    /// its integrity and expiry and returning the original bytes.
    ///
    /// # Errors
    ///
    /// See [`open_with`](Self::open_with).
    pub fn open(&self, sealed: &str) -> Result<Vec<u8>, RequestStateError> {
        self.open_with(sealed, &[])
    }

    /// Opens a sealed value, verifying its integrity against `associated_data`
    /// and checking its expiry.
    ///
    /// `associated_data` must match the bytes passed to
    /// [`SealOptions::associated_data`] when the value was sealed (use `&[]` for
    /// values sealed without it).
    ///
    /// # Errors
    ///
    /// Returns a [`RequestStateError`] if the value is malformed, cannot be
    /// verified, names an unavailable key, or has expired.
    ///
    /// Applications MUST map all token-opening failures to a single
    /// client-facing error and reserve the detailed variants for internal
    /// diagnostics.
    pub fn open_with(
        &self,
        sealed: &str,
        associated_data: &[u8],
    ) -> Result<Vec<u8>, RequestStateError> {
        self.open_at(sealed, associated_data, Self::now_ms())
    }

    /// Opens a sealed value (no associated data) and deserializes its JSON
    /// payload.
    ///
    /// # Errors
    ///
    /// See [`open_json_with`](Self::open_json_with).
    pub fn open_json<T: DeserializeOwned>(&self, sealed: &str) -> Result<T, RequestStateError> {
        self.open_json_with(sealed, &[])
    }

    /// Opens a sealed value against `associated_data` and deserializes its JSON
    /// payload.
    ///
    /// # Errors
    ///
    /// Returns the same integrity, expiry, and format errors as
    /// [`open_with`](Self::open_with), plus [`RequestStateError::Deserialization`]
    /// if the payload is not valid JSON for `T`.
    pub fn open_json_with<T: DeserializeOwned>(
        &self,
        sealed: &str,
        associated_data: &[u8],
    ) -> Result<T, RequestStateError> {
        let payload = self.open_with(sealed, associated_data)?;
        serde_json::from_slice(&payload).map_err(RequestStateError::Deserialization)
    }

    fn seal_at(&self, payload: &[u8], options: &SealOptions<'_>, now_ms: i64) -> String {
        let expiry = match options.ttl {
            Some(ttl) => now_ms.saturating_add(ttl.as_millis().min(i64::MAX as u128) as i64),
            None => 0,
        };

        // body = big-endian expiry (0 = none) followed by the caller payload.
        let mut body = Vec::with_capacity(EXPIRY_LEN + payload.len());
        body.extend_from_slice(&expiry.to_be_bytes());
        body.extend_from_slice(payload);

        match &self.keys {
            Keys::Single(key) => Self::seal_rs1(key, options.associated_data, &body),
            Keys::Ring {
                keys, seal_mode, ..
            } => match seal_mode {
                SealMode::Rs1 { key_id } => Self::seal_rs1(
                    keys.get(key_id).expect("validated rs1 signing key"),
                    options.associated_data,
                    &body,
                ),
                SealMode::Rs2 { key_id } => Self::seal_rs2(
                    key_id,
                    keys.get(key_id).expect("validated rs2 signing key"),
                    options.associated_data,
                    &body,
                ),
            },
        }
    }

    fn open_at(
        &self,
        sealed: &str,
        associated_data: &[u8],
        now_ms: i64,
    ) -> Result<Vec<u8>, RequestStateError> {
        match sealed.split('.').next() {
            Some(VERSION_V1) => self.open_rs1_at(sealed, associated_data, now_ms),
            Some(VERSION_V2) => self.open_rs2_at(sealed, associated_data, now_ms),
            _ => Err(RequestStateError::MalformedFormat),
        }
    }

    fn seal_rs1(key: &[u8], associated_data: &[u8], body: &[u8]) -> String {
        let tag = Self::mac_v1(key, associated_data, body)
            .finalize()
            .into_bytes();
        let mut out = String::with_capacity(
            VERSION_V1.len() + 2 + Self::b64_len(body.len()) + Self::b64_len(tag.len()),
        );
        out.push_str(VERSION_V1);
        out.push('.');
        URL_SAFE_NO_PAD.encode_string(body, &mut out);
        out.push('.');
        URL_SAFE_NO_PAD.encode_string(tag.as_slice(), &mut out);
        out
    }

    fn seal_rs2(kid: &str, key: &[u8], associated_data: &[u8], body: &[u8]) -> String {
        let tag = Self::mac_v2(key, kid.as_bytes(), associated_data, body)
            .finalize()
            .into_bytes();
        let mut out = String::with_capacity(
            VERSION_V2.len()
                + 3
                + Self::b64_len(kid.len())
                + Self::b64_len(body.len())
                + Self::b64_len(tag.len()),
        );
        out.push_str(VERSION_V2);
        out.push('.');
        URL_SAFE_NO_PAD.encode_string(kid.as_bytes(), &mut out);
        out.push('.');
        URL_SAFE_NO_PAD.encode_string(body, &mut out);
        out.push('.');
        URL_SAFE_NO_PAD.encode_string(tag.as_slice(), &mut out);
        out
    }

    fn open_rs1_at(
        &self,
        sealed: &str,
        associated_data: &[u8],
        now_ms: i64,
    ) -> Result<Vec<u8>, RequestStateError> {
        let mut parts = sealed.split('.');
        let version = parts.next().ok_or(RequestStateError::MalformedFormat)?;
        let body_b64 = parts.next().ok_or(RequestStateError::MalformedFormat)?;
        let tag_b64 = parts.next().ok_or(RequestStateError::MalformedFormat)?;
        if parts.next().is_some() || version != VERSION_V1 {
            return Err(RequestStateError::MalformedFormat);
        }

        if matches!(
            &self.keys,
            Keys::Ring { rs1_fallbacks, .. } if rs1_fallbacks.is_empty()
        ) {
            return Err(RequestStateError::UnknownKeyId);
        }

        let body = URL_SAFE_NO_PAD
            .decode(body_b64)
            .map_err(|_| RequestStateError::InvalidEncoding)?;
        let tag = URL_SAFE_NO_PAD
            .decode(tag_b64)
            .map_err(|_| RequestStateError::InvalidEncoding)?;

        // Authentication must not short-circuit based on tag bytes.
        match &self.keys {
            Keys::Single(key) => Self::mac_v1(key, associated_data, &body)
                .verify_slice(&tag)
                .map_err(|_| RequestStateError::IntegrityCheckFailed)?,
            Keys::Ring {
                keys,
                rs1_fallbacks,
                ..
            } => {
                // Try every fallback so timing does not identify the matching key.
                let mut verified = false;
                for kid in rs1_fallbacks {
                    let key = keys.get(kid).expect("validated rs1 fallback key");
                    let matches = Self::mac_v1(key, associated_data, &body)
                        .verify_slice(&tag)
                        .is_ok();
                    verified |= matches;
                }
                if !verified {
                    return Err(RequestStateError::IntegrityCheckFailed);
                }
            }
        }

        Self::open_authenticated_body(body, now_ms)
    }

    fn open_rs2_at(
        &self,
        sealed: &str,
        associated_data: &[u8],
        now_ms: i64,
    ) -> Result<Vec<u8>, RequestStateError> {
        let mut parts = sealed.split('.');
        let version = parts.next().ok_or(RequestStateError::MalformedFormat)?;
        let kid_b64 = parts.next().ok_or(RequestStateError::MalformedFormat)?;
        let body_b64 = parts.next().ok_or(RequestStateError::MalformedFormat)?;
        let tag_b64 = parts.next().ok_or(RequestStateError::MalformedFormat)?;
        if parts.next().is_some() || version != VERSION_V2 {
            return Err(RequestStateError::MalformedFormat);
        }

        if kid_b64.len() > MAX_ENCODED_KID_LEN {
            return Err(RequestStateError::InvalidKeyId);
        }
        let kid = URL_SAFE_NO_PAD
            .decode(kid_b64)
            .map_err(|_| RequestStateError::InvalidEncoding)?;
        if kid.is_empty() || kid.len() > MAX_KID_LEN {
            return Err(RequestStateError::InvalidKeyId);
        }
        let kid = String::from_utf8(kid).map_err(|_| RequestStateError::InvalidKeyId)?;

        let key = match &self.keys {
            Keys::Single(_) => return Err(RequestStateError::UnknownKeyId),
            Keys::Ring { keys, .. } => keys.get(&kid).ok_or(RequestStateError::UnknownKeyId)?,
        };

        let body = URL_SAFE_NO_PAD
            .decode(body_b64)
            .map_err(|_| RequestStateError::InvalidEncoding)?;
        let tag = URL_SAFE_NO_PAD
            .decode(tag_b64)
            .map_err(|_| RequestStateError::InvalidEncoding)?;

        // Authentication must not short-circuit based on tag bytes.
        Self::mac_v2(key, kid.as_bytes(), associated_data, &body)
            .verify_slice(&tag)
            .map_err(|_| RequestStateError::IntegrityCheckFailed)?;

        Self::open_authenticated_body(body, now_ms)
    }

    fn open_authenticated_body(body: Vec<u8>, now_ms: i64) -> Result<Vec<u8>, RequestStateError> {
        // The body is now authenticated, so its framing can be trusted.
        if body.len() < EXPIRY_LEN {
            return Err(RequestStateError::MalformedFormat);
        }
        let expiry = i64::from_be_bytes(body[..EXPIRY_LEN].try_into().expect("checked length"));
        if expiry != 0 && now_ms > expiry {
            return Err(RequestStateError::Expired);
        }

        Ok(body[EXPIRY_LEN..].to_vec())
    }

    fn mac_v1(key: &[u8], associated_data: &[u8], body: &[u8]) -> HmacSha256 {
        let mut mac = HmacSha256::new_from_slice(key).expect("HMAC accepts keys of any length");
        mac.update(DOMAIN_V1);
        mac.update(&(associated_data.len() as u64).to_be_bytes());
        mac.update(associated_data);
        mac.update(body);
        mac
    }

    fn mac_v2(key: &[u8], kid: &[u8], associated_data: &[u8], body: &[u8]) -> HmacSha256 {
        let mut mac = HmacSha256::new_from_slice(key).expect("HMAC accepts keys of any length");
        mac.update(DOMAIN_V2);
        mac.update(&(kid.len() as u64).to_be_bytes());
        mac.update(kid);
        mac.update(&(associated_data.len() as u64).to_be_bytes());
        mac.update(associated_data);
        mac.update(body);
        mac
    }

    fn validate_key_length(key: &[u8]) -> Result<(), RequestStateError> {
        if key.len() < Self::MIN_KEY_LENGTH {
            return Err(RequestStateError::KeyTooShort {
                minimum: Self::MIN_KEY_LENGTH,
                actual: key.len(),
            });
        }
        Ok(())
    }

    fn validate_config_kid(kid: &str) -> Result<(), RequestStateError> {
        if kid.is_empty() {
            return Err(RequestStateError::InvalidKeyring(
                "key id must not be empty",
            ));
        }
        if kid.len() > MAX_KID_LEN {
            return Err(RequestStateError::InvalidKeyring(
                "key id exceeds 255 UTF-8 bytes",
            ));
        }
        Ok(())
    }

    // Base64url without padding encodes at most three bytes as four characters.
    fn b64_len(len: usize) -> usize {
        len.div_ceil(3) * 4
    }

    fn now_ms() -> i64 {
        chrono::Utc::now().timestamp_millis()
    }
}

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

    #[test]
    fn try_new_accepts_key_at_minimum_length() {
        let result = RequestStateCodec::try_new(vec![0; RequestStateCodec::MIN_KEY_LENGTH]);

        assert!(result.is_ok(), "unexpected result: {result:?}");
    }

    #[test]
    fn try_new_rejects_key_below_minimum_length() {
        let actual = RequestStateCodec::MIN_KEY_LENGTH - 1;
        let error = RequestStateCodec::try_new(vec![0; actual]).unwrap_err();

        assert!(
            matches!(
                &error,
                RequestStateError::KeyTooShort {
                    minimum: RequestStateCodec::MIN_KEY_LENGTH,
                    actual: error_actual,
                } if *error_actual == actual
            ),
            "unexpected error: {error}"
        );
    }

    #[test]
    #[allow(deprecated)]
    fn new_accepts_short_key_for_backward_compatibility() {
        let codec = RequestStateCodec::new(b"key".to_vec());

        assert_eq!(codec.open(&codec.seal(b"state")).unwrap(), b"state");
    }

    #[test]
    fn seal_open_roundtrips_bytes() {
        let codec =
            RequestStateCodec::try_new(b"test-key-test-key-test-key-32byte".to_vec()).unwrap();
        let sealed = codec.seal(b"hello world");
        assert!(sealed.starts_with("rs1."));
        assert_eq!(codec.open(&sealed).unwrap(), b"hello world");
    }

    #[test]
    fn seal_open_roundtrips_json() {
        #[derive(serde::Serialize, serde::Deserialize, PartialEq, Debug)]
        struct State {
            tool: String,
            round: u32,
        }
        let codec =
            RequestStateCodec::try_new(b"another-strong-signing-key-here!!".to_vec()).unwrap();
        let state = State {
            tool: "weather".into(),
            round: 3,
        };
        let sealed = codec.seal_json(&state).unwrap();
        let opened: State = codec.open_json(&sealed).unwrap();
        assert_eq!(opened, state);
    }

    #[test]
    fn empty_payload_roundtrips() {
        let codec =
            RequestStateCodec::try_new(b"empty-payload-test-signing-key!!".to_vec()).unwrap();
        let sealed = codec.seal(b"");
        assert_eq!(codec.open(&sealed).unwrap(), b"");
    }

    #[test]
    fn tampered_payload_is_rejected() {
        let codec =
            RequestStateCodec::try_new(b"signing-key-signing-key-signing!!".to_vec()).unwrap();
        let sealed = codec.seal(b"amount=100");

        // Replace the body section but keep the original tag.
        let mut parts: Vec<&str> = sealed.split('.').collect();
        let forged_body = URL_SAFE_NO_PAD.encode(b"amount=999");
        parts[1] = &forged_body;
        let forged = parts.join(".");

        assert!(matches!(
            codec.open(&forged),
            Err(RequestStateError::IntegrityCheckFailed)
        ));
    }

    #[test]
    fn different_key_is_rejected() {
        let signer =
            RequestStateCodec::try_new(b"the-real-signing-key-value-here!!".to_vec()).unwrap();
        let attacker =
            RequestStateCodec::try_new(b"a-totally-different-forged-key!!!".to_vec()).unwrap();
        let sealed = signer.seal(b"trusted");
        assert!(matches!(
            attacker.open(&sealed),
            Err(RequestStateError::IntegrityCheckFailed)
        ));
    }

    #[test]
    fn appended_bytes_are_rejected() {
        let codec =
            RequestStateCodec::try_new(b"key-key-key-key-key-key-key-key!!".to_vec()).unwrap();
        let mut sealed = codec.seal(b"state");
        sealed.push('x');
        assert!(codec.open(&sealed).is_err());
    }

    #[test]
    fn unsupported_version_is_malformed() {
        let codec =
            RequestStateCodec::try_new(b"wrong-version-test-signing-key!!".to_vec()).unwrap();
        let sealed = codec.seal(b"state");
        let bumped = sealed.replacen("rs1.", "rs3.", 1);
        assert!(matches!(
            codec.open(&bumped),
            Err(RequestStateError::MalformedFormat)
        ));
    }

    #[test]
    fn missing_sections_are_malformed() {
        let codec =
            RequestStateCodec::try_new(b"missing-sections-test-signing-key".to_vec()).unwrap();
        assert!(matches!(
            codec.open("rs1"),
            Err(RequestStateError::MalformedFormat)
        ));
        assert!(matches!(
            codec.open("rs1.onlybody"),
            Err(RequestStateError::MalformedFormat)
        ));
        assert!(matches!(
            codec.open("rs1.a.b.c"),
            Err(RequestStateError::MalformedFormat)
        ));
    }

    #[test]
    fn non_base64_sections_are_invalid_encoding() {
        let codec =
            RequestStateCodec::try_new(b"invalid-base64-test-signing-key!!".to_vec()).unwrap();
        assert!(matches!(
            codec.open("rs1.!!!!.!!!!"),
            Err(RequestStateError::InvalidEncoding)
        ));
    }

    #[test]
    fn debug_does_not_leak_key() {
        let codec =
            RequestStateCodec::try_new(b"super-secret-key-super-secret-key!!".to_vec()).unwrap();
        let rendered = format!("{codec:?}");
        assert!(!rendered.contains("super-secret-key"));
        assert!(rendered.contains("redacted"));
    }

    mod associated_data {
        use super::*;

        #[test]
        fn matching_context_opens() {
            let codec =
                RequestStateCodec::try_new(b"key-key-key-key-key-key-key-key!!".to_vec()).unwrap();
            let ctx = b"user:alice|tools/call:weather";
            let sealed = codec.seal_with(b"state", &SealOptions::new().associated_data(ctx));
            assert_eq!(codec.open_with(&sealed, ctx).unwrap(), b"state");
        }

        #[test]
        fn different_context_is_rejected() {
            let codec =
                RequestStateCodec::try_new(b"key-key-key-key-key-key-key-key!!".to_vec()).unwrap();
            let sealed =
                codec.seal_with(b"state", &SealOptions::new().associated_data(b"user:alice"));
            assert!(matches!(
                codec.open_with(&sealed, b"user:bob"),
                Err(RequestStateError::IntegrityCheckFailed)
            ));
        }

        #[test]
        fn missing_context_is_rejected() {
            let codec =
                RequestStateCodec::try_new(b"key-key-key-key-key-key-key-key!!".to_vec()).unwrap();
            let sealed =
                codec.seal_with(b"state", &SealOptions::new().associated_data(b"user:alice"));
            // Opening without the associated data must fail closed.
            assert!(matches!(
                codec.open(&sealed),
                Err(RequestStateError::IntegrityCheckFailed)
            ));
        }
    }

    mod ttl {
        use super::*;

        const KEY: &[u8] = b"ttl-signing-key-ttl-signing-key!!";

        #[test]
        fn within_ttl_opens() {
            let codec = RequestStateCodec::try_new(KEY.to_vec()).unwrap();
            let sealed = codec.seal_at(
                b"state",
                &SealOptions::new().ttl(Duration::from_secs(60)),
                1_000,
            );
            // 30s later, still valid.
            assert_eq!(codec.open_at(&sealed, &[], 31_000).unwrap(), b"state");
        }

        #[test]
        fn past_ttl_is_expired() {
            let codec = RequestStateCodec::try_new(KEY.to_vec()).unwrap();
            let sealed = codec.seal_at(
                b"state",
                &SealOptions::new().ttl(Duration::from_secs(60)),
                1_000,
            );
            // 61s later, expired.
            assert!(matches!(
                codec.open_at(&sealed, &[], 62_000),
                Err(RequestStateError::Expired)
            ));
        }

        #[test]
        fn no_ttl_never_expires() {
            let codec = RequestStateCodec::try_new(KEY.to_vec()).unwrap();
            let sealed = codec.seal_at(b"state", &SealOptions::new(), 1_000);
            assert_eq!(codec.open_at(&sealed, &[], i64::MAX).unwrap(), b"state");
        }

        #[test]
        fn ttl_and_associated_data_combine() {
            let codec = RequestStateCodec::try_new(KEY.to_vec()).unwrap();
            let ctx = b"user:alice";
            let sealed = codec.seal_at(
                b"state",
                &SealOptions::new()
                    .associated_data(ctx)
                    .ttl(Duration::from_secs(60)),
                1_000,
            );
            assert_eq!(codec.open_at(&sealed, ctx, 10_000).unwrap(), b"state");
            assert!(matches!(
                codec.open_at(&sealed, b"user:bob", 10_000),
                Err(RequestStateError::IntegrityCheckFailed)
            ));
            assert!(matches!(
                codec.open_at(&sealed, ctx, 99_000),
                Err(RequestStateError::Expired)
            ));
        }
    }

    mod key_rotation {
        use super::*;

        const KEY_A: &[u8] = b"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";
        const KEY_B: &[u8] = b"bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb";
        const KEY_C: &[u8] = b"cccccccccccccccccccccccccccccccc";
        const KAT_KEY: &[u8] = b"0123456789abcdef0123456789abcdef";
        const KAT_KID: &str = "rotation-key-2026-08";
        const KAT_AD: &[u8] = b"user:alice|request:weather";
        const KAT_NOW_MS: i64 = 1_700_000_000_000;

        fn two_key_ring(active: &str) -> RequestStateCodec {
            RequestStateCodec::new_with_keyring(active, [("a", KEY_A), ("b", KEY_B)]).unwrap()
        }

        fn body(expiry: i64, payload: &[u8]) -> Vec<u8> {
            let mut body = expiry.to_be_bytes().to_vec();
            body.extend_from_slice(payload);
            body
        }

        fn replace_segment(token: &str, index: usize, replacement: &str) -> String {
            let mut parts: Vec<String> = token.split('.').map(str::to_owned).collect();
            parts[index] = replacement.to_owned();
            parts.join(".")
        }

        fn test_mac(
            key: &[u8],
            domain: &[u8],
            kid: Option<&[u8]>,
            associated_data: &[u8],
            body: &[u8],
        ) -> Vec<u8> {
            let mut mac = HmacSha256::new_from_slice(key).expect("HMAC accepts keys of any length");
            mac.update(domain);
            if let Some(kid) = kid {
                mac.update(&(kid.len() as u64).to_be_bytes());
                mac.update(kid);
            }
            mac.update(&(associated_data.len() as u64).to_be_bytes());
            mac.update(associated_data);
            mac.update(body);
            mac.finalize().into_bytes().to_vec()
        }

        fn raw_rs1(body: &[u8], tag: &[u8]) -> String {
            format!(
                "rs1.{}.{}",
                URL_SAFE_NO_PAD.encode(body),
                URL_SAFE_NO_PAD.encode(tag)
            )
        }

        fn raw_rs2(kid: &[u8], body: &[u8], tag: &[u8]) -> String {
            format!(
                "rs2.{}.{}.{}",
                URL_SAFE_NO_PAD.encode(kid),
                URL_SAFE_NO_PAD.encode(body),
                URL_SAFE_NO_PAD.encode(tag)
            )
        }

        #[test]
        fn rs1_known_answer_is_unchanged() {
            // Independently checked with Python stdlib HMAC and Ruby OpenSSL.
            let codec = RequestStateCodec::try_new(KAT_KEY).unwrap();
            let sealed = codec.seal_at(
                b"step=2",
                &SealOptions::new()
                    .associated_data(KAT_AD)
                    .ttl(Duration::from_secs(90)),
                KAT_NOW_MS,
            );
            assert_eq!(
                sealed,
                "rs1.AAABi8_mx5BzdGVwPTI.GQgS0X7mtSz8ZOy_kld2Zjuc4gAMGpBL74EghWI36IQ"
            );
        }

        #[test]
        fn rs2_known_answer_matches_wire_specification() {
            // Independently checked with Python stdlib HMAC and Ruby OpenSSL.
            let codec = RequestStateCodec::new_with_keyring(KAT_KID, [(KAT_KID, KAT_KEY)]).unwrap();
            let sealed = codec.seal_at(
                b"step=2",
                &SealOptions::new()
                    .associated_data(KAT_AD)
                    .ttl(Duration::from_secs(90)),
                KAT_NOW_MS,
            );
            assert_eq!(
                sealed,
                "rs2.cm90YXRpb24ta2V5LTIwMjYtMDg.AAABi8_mx5BzdGVwPTI.twv2acu7lKXqebyrmit-JrHHZm-BkKlBQEMMtL3lHk8"
            );
        }

        #[test]
        fn rs2_roundtrips_with_associated_data_and_ttl() {
            let codec = two_key_ring("a");
            let options = SealOptions::new()
                .associated_data(b"user:alice")
                .ttl(Duration::from_secs(60));

            let sealed = codec.seal_at(b"state", &options, 1_000);
            assert!(sealed.starts_with("rs2.YQ."));
            assert_eq!(
                codec.open_at(&sealed, b"user:alice", 30_000).unwrap(),
                b"state"
            );
            assert!(matches!(
                codec.open_at(&sealed, b"user:bob", 30_000),
                Err(RequestStateError::IntegrityCheckFailed)
            ));
            assert!(matches!(
                codec.open_at(&sealed, b"user:alice", 70_000),
                Err(RequestStateError::Expired)
            ));
        }

        #[test]
        fn rotation_keeps_previous_rs2_key_verifiable() {
            let signer_a = two_key_ring("a");
            let token_a = signer_a.seal(b"state-a");

            let signer_b = two_key_ring("b");
            assert_eq!(signer_b.open(&token_a).unwrap(), b"state-a");
            let token_b = signer_b.seal(b"state-b");
            assert!(token_b.starts_with("rs2.Yg."));
            assert_eq!(signer_b.open(&token_b).unwrap(), b"state-b");

            let without_a = RequestStateCodec::new_with_keyring("b", [("b", KEY_B)]).unwrap();
            assert!(matches!(
                without_a.open(&token_a),
                Err(RequestStateError::UnknownKeyId)
            ));
        }

        #[test]
        fn rolling_migration_is_bidirectionally_compatible() {
            let old = RequestStateCodec::try_new(KEY_A).unwrap();
            let transitional =
                RequestStateCodec::new_with_keyring("new", [("old", KEY_A), ("new", KEY_B)])
                    .unwrap()
                    .with_rs1_signing("old")
                    .unwrap();
            let promoted =
                RequestStateCodec::new_with_keyring("new", [("old", KEY_A), ("new", KEY_B)])
                    .unwrap()
                    .with_rs1_fallback("old")
                    .unwrap();
            let retired = RequestStateCodec::new_with_keyring("new", [("new", KEY_B)]).unwrap();

            let old_token = old.seal(b"old");
            assert_eq!(transitional.open(&old_token).unwrap(), b"old");

            let transitional_token = transitional.seal(b"transition");
            assert!(transitional_token.starts_with("rs1."));
            assert_eq!(old.open(&transitional_token).unwrap(), b"transition");
            assert_eq!(promoted.open(&transitional_token).unwrap(), b"transition");

            let promoted_token = promoted.seal(b"promoted");
            assert!(promoted_token.starts_with("rs2."));
            assert_eq!(transitional.open(&promoted_token).unwrap(), b"promoted");
            assert_eq!(retired.open(&promoted_token).unwrap(), b"promoted");
            assert!(matches!(
                retired.open(&old_token),
                Err(RequestStateError::UnknownKeyId)
            ));
        }

        #[test]
        fn multiple_legacy_fallbacks_are_supported() {
            let legacy_a = RequestStateCodec::try_new(KEY_A).unwrap().seal(b"a");
            let legacy_b = RequestStateCodec::try_new(KEY_B).unwrap().seal(b"b");
            let legacy_c = RequestStateCodec::try_new(KEY_C).unwrap().seal(b"c");
            let ring = RequestStateCodec::new_with_keyring(
                "new",
                [("a", KEY_A), ("b", KEY_B), ("new", KEY_C)],
            )
            .unwrap()
            .with_rs1_fallback("a")
            .unwrap()
            .with_rs1_fallback("b")
            .unwrap();

            assert_eq!(ring.open(&legacy_a).unwrap(), b"a");
            assert_eq!(ring.open(&legacy_b).unwrap(), b"b");
            assert!(matches!(
                ring.open(&legacy_c),
                Err(RequestStateError::IntegrityCheckFailed)
            ));
        }

        #[test]
        fn kid_is_authenticated_even_when_ids_share_key_bytes() {
            let codec =
                RequestStateCodec::new_with_keyring("a", [("a", KEY_A), ("b", KEY_A)]).unwrap();
            let sealed = codec.seal(b"state");
            let swapped = replace_segment(&sealed, 1, &URL_SAFE_NO_PAD.encode(b"b"));
            assert!(matches!(
                codec.open(&swapped),
                Err(RequestStateError::IntegrityCheckFailed)
            ));
        }

        #[test]
        fn independent_rs2_segment_tampering_is_rejected() {
            let codec = two_key_ring("a");
            let sealed = codec.seal(b"state");

            let swapped_kid = replace_segment(&sealed, 1, &URL_SAFE_NO_PAD.encode(b"b"));
            let tampered_body = replace_segment(&sealed, 2, &URL_SAFE_NO_PAD.encode(b"changed"));
            let tampered_tag = replace_segment(&sealed, 3, &URL_SAFE_NO_PAD.encode([0_u8; 32]));

            for tampered in [swapped_kid, tampered_body, tampered_tag] {
                assert!(matches!(
                    codec.open(&tampered),
                    Err(RequestStateError::IntegrityCheckFailed)
                ));
            }
        }

        #[test]
        fn version_domains_are_cryptographically_separate() {
            let token_body = body(0, b"state");

            let wrong_v2_tag = test_mac(KEY_A, DOMAIN_V1, Some(b"a"), b"", &token_body);
            let wrong_v2 = raw_rs2(b"a", &token_body, &wrong_v2_tag);
            assert!(matches!(
                two_key_ring("a").open(&wrong_v2),
                Err(RequestStateError::IntegrityCheckFailed)
            ));

            let wrong_v1_tag = test_mac(KEY_A, DOMAIN_V2, None, b"", &token_body);
            let wrong_v1 = raw_rs1(&token_body, &wrong_v1_tag);
            assert!(matches!(
                RequestStateCodec::try_new(KEY_A).unwrap().open(&wrong_v1),
                Err(RequestStateError::IntegrityCheckFailed)
            ));
        }

        #[test]
        fn constructor_invariants_are_enforced() {
            let empty =
                RequestStateCodec::new_with_keyring("a", std::iter::empty::<(&str, &[u8])>());
            assert!(matches!(empty, Err(RequestStateError::InvalidKeyring(_))));

            let duplicate = RequestStateCodec::new_with_keyring("a", [("a", KEY_A), ("a", KEY_B)]);
            assert!(matches!(
                duplicate,
                Err(RequestStateError::InvalidKeyring(_))
            ));

            let empty_kid = RequestStateCodec::new_with_keyring("", [("", KEY_A)]);
            assert!(matches!(
                empty_kid,
                Err(RequestStateError::InvalidKeyring(_))
            ));

            let oversized = "x".repeat(MAX_KID_LEN + 1);
            let oversized_kid =
                RequestStateCodec::new_with_keyring(oversized.clone(), [(oversized, KEY_A)]);
            assert!(matches!(
                oversized_kid,
                Err(RequestStateError::InvalidKeyring(_))
            ));

            let absent_active = RequestStateCodec::new_with_keyring("missing", [("a", KEY_A)]);
            assert!(matches!(
                absent_active,
                Err(RequestStateError::InvalidKeyring(_))
            ));

            let short_key = RequestStateCodec::new_with_keyring(
                "a",
                [("a", vec![0; RequestStateCodec::MIN_KEY_LENGTH - 1])],
            );
            assert!(matches!(
                short_key,
                Err(RequestStateError::KeyTooShort { .. })
            ));

            assert!(matches!(
                RequestStateCodec::try_new(KEY_A)
                    .unwrap()
                    .with_rs1_signing("a"),
                Err(RequestStateError::InvalidKeyring(_))
            ));
            assert!(matches!(
                two_key_ring("a").with_rs1_signing("missing"),
                Err(RequestStateError::InvalidKeyring(_))
            ));
            assert!(matches!(
                RequestStateCodec::try_new(KEY_A)
                    .unwrap()
                    .with_rs1_fallback("a"),
                Err(RequestStateError::InvalidKeyring(_))
            ));
            assert!(matches!(
                two_key_ring("a").with_rs1_fallback("missing"),
                Err(RequestStateError::InvalidKeyring(_))
            ));
        }

        #[test]
        fn maximum_length_kid_roundtrips_and_oversized_wire_kid_is_rejected() {
            let max_kid = "x".repeat(MAX_KID_LEN);
            let codec =
                RequestStateCodec::new_with_keyring(max_kid.clone(), [(max_kid, KEY_A)]).unwrap();
            let token = codec.seal(b"state");
            assert_eq!(codec.open(&token).unwrap(), b"state");

            let encoded_oversized = URL_SAFE_NO_PAD.encode("x".repeat(MAX_KID_LEN + 1));
            assert!(encoded_oversized.len() > MAX_ENCODED_KID_LEN);
            let oversized = format!("rs2.{encoded_oversized}.!!!!.!!!!");
            assert!(matches!(
                codec.open(&oversized),
                Err(RequestStateError::InvalidKeyId)
            ));

            let overlong_invalid_base64 =
                format!("rs2.{}.!!!!.!!!!", "!".repeat(MAX_ENCODED_KID_LEN + 1));
            assert!(matches!(
                codec.open(&overlong_invalid_base64),
                Err(RequestStateError::InvalidKeyId)
            ));
        }

        #[test]
        fn parser_rejects_invalid_tokens_and_unavailable_keys() {
            let codec = two_key_ring("a");
            for malformed in [
                "rs2",
                "rs2.YQ",
                "rs2.YQ.body",
                "rs2.YQ.body.tag.extra",
                "rs3.YQ.body.tag",
            ] {
                assert!(matches!(
                    codec.open(malformed),
                    Err(RequestStateError::MalformedFormat)
                ));
            }

            let valid_rs2 = codec.seal(b"state");
            assert!(matches!(
                codec.open(&replace_segment(&valid_rs2, 1, "!!!!")),
                Err(RequestStateError::InvalidEncoding)
            ));
            assert!(matches!(
                codec.open(&replace_segment(&valid_rs2, 1, "")),
                Err(RequestStateError::InvalidKeyId)
            ));
            let non_utf8 = URL_SAFE_NO_PAD.encode([0xff]);
            assert!(matches!(
                codec.open(&replace_segment(&valid_rs2, 1, &non_utf8)),
                Err(RequestStateError::InvalidKeyId)
            ));

            assert!(matches!(
                RequestStateCodec::try_new(KEY_A).unwrap().open(&valid_rs2),
                Err(RequestStateError::UnknownKeyId)
            ));

            let valid_rs1 = RequestStateCodec::try_new(KEY_A).unwrap().seal(b"state");
            assert!(matches!(
                codec.open(&valid_rs1),
                Err(RequestStateError::UnknownKeyId)
            ));
        }

        #[test]
        fn authenticated_short_body_is_malformed() {
            let short_body = b"short";
            let tag = RequestStateCodec::mac_v2(KEY_A, b"a", b"", short_body)
                .finalize()
                .into_bytes();
            let token = raw_rs2(b"a", short_body, tag.as_slice());
            assert!(matches!(
                two_key_ring("a").open(&token),
                Err(RequestStateError::MalformedFormat)
            ));
        }

        #[test]
        fn serde_is_reached_only_after_integrity_verification() {
            let codec = two_key_ring("a");
            let invalid_json = codec.seal(b"{not-json");
            let opened: Result<serde_json::Value, _> = codec.open_json(&invalid_json);
            assert!(matches!(opened, Err(RequestStateError::Deserialization(_))));

            let valid_json = codec.seal(b"{}");
            let tampered_body = body(0, b"{not-json");
            let tampered = replace_segment(&valid_json, 2, &URL_SAFE_NO_PAD.encode(tampered_body));
            let opened: Result<serde_json::Value, _> = codec.open_json(&tampered);
            assert!(matches!(
                opened,
                Err(RequestStateError::IntegrityCheckFailed)
            ));
        }

        #[test]
        fn ring_debug_redacts_all_key_material() {
            let codec = two_key_ring("b").with_rs1_fallback("a").unwrap();
            let rendered = format!("{codec:?}");
            assert!(!rendered.contains(std::str::from_utf8(KEY_A).unwrap()));
            assert!(!rendered.contains(std::str::from_utf8(KEY_B).unwrap()));
            assert!(rendered.contains("redacted"));
        }

        #[test]
        fn mutated_tokens_do_not_panic() {
            let codec = two_key_ring("a").with_rs1_fallback("a").unwrap();
            let valid = [
                RequestStateCodec::try_new(KEY_A).unwrap().seal(b"state"),
                codec.seal(b"state"),
            ];
            let mut corpus = vec![
                String::new(),
                ".".to_owned(),
                "...".to_owned(),
                "rs1".to_owned(),
                "rs2".to_owned(),
                "💥".to_owned(),
                "rs2.💥...".to_owned(),
            ];

            for token in valid {
                for end in 0..=token.len() {
                    corpus.push(token[..end].to_owned());
                }
                for index in 0..token.len() {
                    let mut bytes = token.as_bytes().to_vec();
                    bytes[index] = b'!';
                    corpus.push(String::from_utf8(bytes).expect("token is ASCII"));
                }
            }

            for candidate in corpus {
                let _ = codec.open(&candidate);
                let _ = codec.open_with(&candidate, b"context");
            }
        }
    }
}