footing 0.5.3

Feature-gated foundations for Rust backend services
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
//! Small cryptographic building blocks for application glue code.
//!
//! The module intentionally stays below business protocols. It provides secure
//! random tokens and bytes, token hashing, PKCE S256 helpers, numeric
//! verification codes, constant-time comparison, and signed tokens that
//! can rotate verification keys.
//!
//! Signed token payloads are readable; signing provides authentication, not
//! confidentiality. Persistent credential encryption and key management are
//! outside this module's scope. An encryption adapter should use a maintained
//! AEAD implementation or managed key service, bind purpose and record identity
//! as authenticated context, and own its versioned ciphertext format and rotation
//! policy. [`crate::secret`] supplies redacted secret containers for that boundary.
//!
//! ```rust
//! use footing::crypto::{SignedTokenCodec, TokenGenerator};
//! use footing::secret::ExposeSecret;
//!
//! let token = TokenGenerator::default().generate().unwrap();
//! assert!(!token.expose_secret().is_empty());
//!
//! let codec = SignedTokenCodec::new(b"01234567890123456789012345678901").unwrap();
//! let signed = codec.encode(&serde_json::json!({ "sub": "usr_01" })).unwrap();
//! let decoded: serde_json::Value = codec.decode(&signed).unwrap();
//! assert_eq!(decoded["sub"], "usr_01");
//! ```
//!
use base64::{Engine as _, engine::general_purpose::URL_SAFE_NO_PAD};
use ctutils::CtEq as _;
use serde::{Serialize, de::DeserializeOwned};
use sha2::{Digest as _, Sha256};
use thiserror::Error;

use crate::result::{ClassifyError, ErrorKind};
use crate::secret::SecretString;
use crate::signing::SigningKeys;

/// Minimum signing key size for HMAC-SHA256 tokens.
pub const MIN_SIGNING_KEY_BYTES: usize = crate::signing::MIN_SIGNING_KEY_BYTES;

/// Default random token entropy.
pub const DEFAULT_TOKEN_BYTES: usize = 32;

/// Maximum accepted signed token length.
pub const DEFAULT_MAX_SIGNED_TOKEN_BYTES: usize = 8 * 1024;

/// Maximum supported numeric code length.
pub const MAX_NUMERIC_CODE_DIGITS: u32 = 18;

/// Compares byte contents using RustCrypto's constant-time equality primitive.
///
/// Slice lengths are not secret; callers that need to hide them must compare
/// fixed-size values, such as hashes or MACs.
#[must_use]
pub fn constant_time_eq(left: &[u8], right: &[u8]) -> bool {
    left.ct_eq(right).to_bool()
}

/// Generates random bytes from the operating system secure random source.
pub fn random_bytes(length: usize) -> Result<Vec<u8>, CryptoError> {
    if length == 0 {
        return Err(CryptoError::InvalidTokenSize);
    }

    let mut bytes = vec![0_u8; length];
    getrandom::fill(&mut bytes).map_err(|_| CryptoError::Random)?;
    Ok(bytes)
}

/// Generates a fixed-size random byte array.
pub fn random_array<const N: usize>() -> Result<[u8; N], CryptoError> {
    if N == 0 {
        return Err(CryptoError::InvalidTokenSize);
    }

    let mut bytes = [0_u8; N];
    getrandom::fill(&mut bytes).map_err(|_| CryptoError::Random)?;
    Ok(bytes)
}

/// Hashes bytes with SHA-256 and encodes the digest as URL-safe base64 without padding.
#[must_use]
pub fn sha256_urlsafe(value: impl AsRef<[u8]>) -> String {
    URL_SAFE_NO_PAD.encode(Sha256::digest(value.as_ref()))
}

/// Hashes multiple byte strings with SHA-256 and URL-safe base64 without padding.
/// Each part is prefixed by its byte length as a big-endian `u64`, so boundaries
/// remain unambiguous when composing lookup keys or token scopes.
#[must_use]
pub fn sha256_urlsafe_parts<I, P>(parts: I) -> String
where
    I: IntoIterator<Item = P>,
    P: AsRef<[u8]>,
{
    let mut hasher = Sha256::new();
    for part in parts {
        let part = part.as_ref();
        let len = part.len() as u64;
        hasher.update(len.to_be_bytes());
        hasher.update(part);
    }
    URL_SAFE_NO_PAD.encode(hasher.finalize())
}

/// Computes the PKCE S256 transformation for a verifier.
///
/// Callers generating challenges must supply an RFC 7636 verifier: 43–128 ASCII
/// letters, digits, or `-._~`. [`verify_pkce_s256`] enforces that syntax before
/// comparing challenges.
#[must_use]
pub fn pkce_s256_challenge(verifier: &str) -> String {
    sha256_urlsafe(verifier.as_bytes())
}

/// Verifies a PKCE S256 challenge, rejecting malformed RFC 7636 verifiers.
#[must_use]
pub fn verify_pkce_s256(verifier: &str, expected_challenge: &str) -> bool {
    if !(43..=128).contains(&verifier.len())
        || !verifier
            .bytes()
            .all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'-' | b'.' | b'_' | b'~'))
    {
        return false;
    }
    let actual = pkce_s256_challenge(verifier);
    constant_time_eq(actual.as_bytes(), expected_challenge.as_bytes())
}

/// Generates URL-safe random tokens.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub struct TokenGenerator {
    token_bytes: usize,
}

impl Default for TokenGenerator {
    fn default() -> Self {
        Self {
            token_bytes: DEFAULT_TOKEN_BYTES,
        }
    }
}

impl TokenGenerator {
    /// Creates a token generator.
    pub const fn new(token_bytes: usize) -> Result<Self, CryptoError> {
        if token_bytes == 0 {
            return Err(CryptoError::InvalidTokenSize);
        }
        Ok(Self { token_bytes })
    }

    /// Returns the number of random bytes used per token.
    #[must_use]
    pub const fn token_bytes(&self) -> usize {
        self.token_bytes
    }

    /// Generates a URL-safe token with redacted formatting and zeroization on drop.
    pub fn generate(&self) -> Result<SecretString, CryptoError> {
        let bytes = random_bytes(self.token_bytes)?;
        Ok(SecretString::new(URL_SAFE_NO_PAD.encode(bytes)))
    }
}

/// Generates human-entered numeric verification codes.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub struct NumericCodeGenerator {
    digits: u32,
}

impl NumericCodeGenerator {
    /// Creates a numeric code generator.
    pub const fn new(digits: u32) -> Result<Self, CryptoError> {
        if digits == 0 || digits > MAX_NUMERIC_CODE_DIGITS {
            return Err(CryptoError::InvalidNumericCodeDigits {
                min_digits: 1,
                max_digits: MAX_NUMERIC_CODE_DIGITS,
            });
        }
        Ok(Self { digits })
    }

    /// Returns the configured number of digits.
    #[must_use]
    pub const fn digits(&self) -> u32 {
        self.digits
    }

    /// Generates a zero-padded numeric code using unbiased rejection sampling.
    pub fn generate(&self) -> Result<String, CryptoError> {
        let modulo = 10_u64.pow(self.digits);
        let value = random_u64_below(modulo)?;
        Ok(format!("{value:0width$}", width = self.digits as usize))
    }
}

const TOKEN_SIGNING_DOMAIN: &[u8] = b"footing:signed-token:v2\0";

/// Encodes and verifies signed JSON tokens using the `v2` wire format.
///
/// The signature includes a fixed purpose and version, preventing signed
/// cursors from being used as tokens even when both codecs share a key.
/// Tokens issued with the old `v1` format must be reissued.
#[derive(Debug, Clone)]
#[non_exhaustive]
pub struct SignedTokenCodec {
    keys: SigningKeys,
    max_token_bytes: usize,
}

impl SignedTokenCodec {
    /// Creates a codec with the active signing key.
    pub fn new(active_key: impl AsRef<[u8]>) -> Result<Self, CryptoError> {
        Ok(Self {
            keys: SigningKeys::new(active_key).map_err(|_| CryptoError::InvalidSigningKey {
                min_bytes: MIN_SIGNING_KEY_BYTES,
            })?,
            max_token_bytes: DEFAULT_MAX_SIGNED_TOKEN_BYTES,
        })
    }

    /// Adds one previous verification key for key rotation.
    pub fn with_previous_key(mut self, key: impl AsRef<[u8]>) -> Result<Self, CryptoError> {
        self.keys
            .add_previous(key)
            .map_err(|_| CryptoError::InvalidSigningKey {
                min_bytes: MIN_SIGNING_KEY_BYTES,
            })?;
        Ok(self)
    }

    /// Adds multiple previous verification keys for key rotation.
    pub fn with_previous_keys<I, K>(mut self, keys: I) -> Result<Self, CryptoError>
    where
        I: IntoIterator<Item = K>,
        K: AsRef<[u8]>,
    {
        for key in keys {
            self = self.with_previous_key(key)?;
        }
        Ok(self)
    }

    /// Sets the maximum accepted signed token size.
    pub fn with_max_token_bytes(mut self, max_token_bytes: usize) -> Result<Self, CryptoError> {
        if max_token_bytes == 0 {
            return Err(CryptoError::InvalidSignedTokenMaxBytes);
        }
        self.max_token_bytes = max_token_bytes;
        Ok(self)
    }

    /// Encodes and signs a serializable payload.
    pub fn encode<T>(&self, value: &T) -> Result<String, CryptoError>
    where
        T: Serialize + ?Sized,
    {
        let bytes = serde_json::to_vec(value).map_err(|_| CryptoError::Serialization)?;
        let payload = URL_SAFE_NO_PAD.encode(bytes);
        let signature = self
            .keys
            .sign(TOKEN_SIGNING_DOMAIN, payload.as_bytes())
            .map_err(|_| CryptoError::InvalidSigningKey {
                min_bytes: MIN_SIGNING_KEY_BYTES,
            })?;
        let token = format!("v2.{payload}.{signature}");
        validate_signed_token_length(&token, self.max_token_bytes)?;
        Ok(token)
    }

    /// Verifies and decodes a signed token.
    pub fn decode<T>(&self, token: &str) -> Result<T, CryptoError>
    where
        T: DeserializeOwned,
    {
        validate_signed_token_length(token, self.max_token_bytes)?;
        let (version, rest) = token.split_once('.').ok_or(CryptoError::InvalidToken)?;
        if version != "v2" {
            return Err(CryptoError::UnsupportedTokenVersion);
        }
        let (payload, signature) = rest.split_once('.').ok_or(CryptoError::InvalidToken)?;
        self.keys
            .verify(TOKEN_SIGNING_DOMAIN, payload.as_bytes(), signature)
            .map_err(|_| CryptoError::InvalidSignature)?;
        let bytes = URL_SAFE_NO_PAD
            .decode(payload)
            .map_err(|_| CryptoError::InvalidToken)?;
        serde_json::from_slice(&bytes).map_err(|_| CryptoError::Serialization)
    }
}

/// Crypto helper errors.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Error)]
#[non_exhaustive]
pub enum CryptoError {
    /// Token size must be non-zero.
    #[error("token size must be greater than zero")]
    InvalidTokenSize,
    /// Numeric code size is unsupported.
    #[error("numeric code digits must be between {min_digits} and {max_digits}")]
    InvalidNumericCodeDigits {
        #[doc = "The minimum number of digits."]
        min_digits: u32,
        #[doc = "The maximum number of digits."]
        max_digits: u32,
    },
    /// Random integer upper bound is invalid.
    #[error("random integer upper bound must be greater than zero")]
    InvalidRandomBound,
    /// Random source failed.
    #[error("secure random source failed")]
    Random,
    /// Signing key is too short.
    #[error("signing key must be at least {min_bytes} bytes")]
    InvalidSigningKey {
        #[doc = "The minimum number of bytes."]
        min_bytes: usize,
    },
    /// Token exceeds the configured maximum length.
    #[error("signed token is too large")]
    TokenTooLarge,
    /// Signed token maximum length is invalid.
    #[error("signed token max bytes must be greater than zero")]
    InvalidSignedTokenMaxBytes,
    /// Token shape is invalid.
    #[error("signed token is invalid")]
    InvalidToken,
    /// Token version is unsupported.
    #[error("signed token version is unsupported")]
    UnsupportedTokenVersion,
    /// Token signature is invalid.
    #[error("signed token signature is invalid")]
    InvalidSignature,
    /// JSON serialization or deserialization failed.
    #[error("signed token payload serialization failed")]
    Serialization,
}

impl ClassifyError for CryptoError {
    fn error_kind(&self) -> ErrorKind {
        match self {
            Self::InvalidTokenSize
            | Self::InvalidNumericCodeDigits { .. }
            | Self::InvalidRandomBound
            | Self::InvalidSigningKey { .. }
            | Self::TokenTooLarge
            | Self::InvalidSignedTokenMaxBytes
            | Self::InvalidToken
            | Self::UnsupportedTokenVersion
            | Self::InvalidSignature
            | Self::Serialization => ErrorKind::Validation,
            Self::Random => ErrorKind::Unavailable,
        }
    }

    fn error_code(&self) -> crate::result::ErrorCode {
        crate::result::ErrorCode::internal(match self {
            Self::InvalidTokenSize => "invalid_token_size",
            Self::InvalidNumericCodeDigits { .. } => "invalid_numeric_code_digits",
            Self::InvalidRandomBound => "invalid_random_bound",
            Self::Random => "secure_random_unavailable",
            Self::InvalidSigningKey { .. } => "invalid_signing_key",
            Self::TokenTooLarge => "token_too_large",
            Self::InvalidSignedTokenMaxBytes => "invalid_signed_token_max_bytes",
            Self::InvalidToken => "invalid_token",
            Self::UnsupportedTokenVersion => "unsupported_token_version",
            Self::InvalidSignature => "invalid_signature",
            Self::Serialization => "token_serialization_failed",
        })
    }
}

fn validate_signed_token_length(token: &str, max_token_bytes: usize) -> Result<(), CryptoError> {
    if token.len() > max_token_bytes {
        return Err(CryptoError::TokenTooLarge);
    }
    Ok(())
}

fn random_u64_below(upper_bound: u64) -> Result<u64, CryptoError> {
    if upper_bound == 0 {
        return Err(CryptoError::InvalidRandomBound);
    }

    let acceptance_zone = u64::MAX - (u64::MAX % upper_bound);
    loop {
        let candidate = u64::from_be_bytes(random_array::<8>()?);
        if candidate < acceptance_zone {
            return Ok(candidate % upper_bound);
        }
    }
}

#[cfg(test)]
mod tests {
    use serde_json::json;

    use super::*;
    use crate::secret::ExposeSecret;

    const KEY: &[u8] = b"01234567890123456789012345678901";
    const OLD_KEY: &[u8] = b"abcdefghijklmnopqrstuvwxyz123456";

    #[test]
    fn constant_time_compare_requires_same_bytes() {
        assert!(constant_time_eq(b"", b""));
        assert!(constant_time_eq(b"same", b"same"));
        assert!(!constant_time_eq(b"same", b"diff"));
        assert!(!constant_time_eq(b"same", b"same-but-longer"));
        assert!(!constant_time_eq(b"same", b"same\0"));
        assert!(!constant_time_eq(b"same\0", b"same"));
        assert!(!constant_time_eq(b"", b"\0"));
        for index in 0..32 {
            let original = [0_u8; 32];
            let mut changed = original;
            changed[index] = 1;
            assert!(!constant_time_eq(&original, &changed));
        }
    }

    #[test]
    fn token_generator_returns_redacted_url_safe_token() {
        let token: SecretString = TokenGenerator::new(16)
            .expect("valid token size")
            .generate()
            .expect("token should generate");

        assert_eq!(
            URL_SAFE_NO_PAD.decode(token.expose_secret()).unwrap().len(),
            16
        );
        assert_eq!(format!("{token:?}"), "[REDACTED]");
        assert_eq!(format!("{token}"), "[REDACTED]");
    }

    #[test]
    fn random_numeric_code_is_zero_padded() {
        let code = NumericCodeGenerator::new(8)
            .expect("valid digits")
            .generate()
            .expect("code should generate");

        assert_eq!(code.len(), 8);
        assert!(code.chars().all(|ch| ch.is_ascii_digit()));
    }

    #[test]
    fn hashes_key_parts_with_stable_unambiguous_length_prefixes() {
        assert_eq!(
            sha256_urlsafe_parts([b"ab".as_slice(), b"c".as_slice()]),
            "YB1UduLM_iyHorunoyJllzSgV0nVtap4H1E-SRLbDV8"
        );
        assert_ne!(
            sha256_urlsafe_parts([b"ab".as_slice(), b"c".as_slice()]),
            sha256_urlsafe_parts([b"a".as_slice(), b"bc".as_slice()])
        );
        assert_ne!(sha256_urlsafe(b"token"), sha256_urlsafe_parts([b"token"]));
    }

    #[test]
    fn pkce_s256_matches_rfc_vector() {
        let verifier = "dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk";

        assert_eq!(
            pkce_s256_challenge(verifier),
            "E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cM"
        );
        assert!(verify_pkce_s256(
            verifier,
            "E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cM"
        ));
        assert!(!verify_pkce_s256(verifier, "invalid"));
    }

    #[test]
    fn pkce_checks_verifier_syntax_at_the_security_boundary() {
        for verifier in [
            String::new(),
            "a".repeat(42),
            "a".repeat(129),
            format!("{} ", "a".repeat(42)),
            format!("{}+", "a".repeat(42)),
            format!("{}=", "a".repeat(42)),
            format!("{}\0", "a".repeat(42)),
            "é".repeat(32),
        ] {
            assert!(!verify_pkce_s256(
                &verifier,
                &pkce_s256_challenge(&verifier)
            ));
        }
        for verifier in ["a".repeat(43), "a".repeat(128), "AZaz09-._~".repeat(8)] {
            assert!(verify_pkce_s256(&verifier, &pkce_s256_challenge(&verifier)));
        }
    }

    #[test]
    fn signed_token_uses_versioned_domain_and_validates_keys() {
        let codec = SignedTokenCodec::new(KEY)
            .unwrap()
            .with_previous_keys([OLD_KEY])
            .unwrap();
        // HMAC-SHA256 over the fixed domain followed by the encoded payload.
        let expected = "v2.eyJzdWIiOiJ1c3JfMDEifQ.9GM4vBg8_DyUMapinzt-35sC61awL5-lcklsghtJ71g";
        assert_eq!(codec.encode(&json!({"sub": "usr_01"})).unwrap(), expected);
        assert_eq!(
            codec.decode::<serde_json::Value>(expected).unwrap(),
            json!({"sub": "usr_01"})
        );
        for signature in ["", "!", "AA", "A".repeat(43).as_str()] {
            assert_eq!(
                codec
                    .decode::<serde_json::Value>(&format!("v2.eyJzdWIiOiJ1c3JfMDEifQ.{signature}")),
                Err(CryptoError::InvalidSignature)
            );
        }
        assert!(SignedTokenCodec::new(b"short").is_err());
        assert!(codec.clone().with_previous_key(b"short").is_err());
        let debug = format!("{codec:?}");
        for key in [KEY, OLD_KEY] {
            assert!(!debug.contains(std::str::from_utf8(key).unwrap()));
        }
        assert!(debug.contains("redacted"));
    }

    #[test]
    fn signed_token_rejects_legacy_signatures_and_changed_versions() {
        let codec = SignedTokenCodec::new(KEY).unwrap();
        let legacy = "v1.eyJzdWIiOiJ1c3JfMDEifQ.nf4CI4DU1v4TPMbeCCYao9DpuCKrgyEVBH8q8ZUYSy0";
        assert_eq!(
            codec.decode::<serde_json::Value>(legacy),
            Err(CryptoError::UnsupportedTokenVersion)
        );
        assert_eq!(
            codec.decode::<serde_json::Value>(&legacy.replacen("v1.", "v2.", 1)),
            Err(CryptoError::InvalidSignature)
        );
        let token = codec.encode(&json!({"sub": "usr_01"})).unwrap();
        assert_eq!(
            codec.decode::<serde_json::Value>(&token.replacen("v2.", "v3.", 1)),
            Err(CryptoError::UnsupportedTokenVersion)
        );
    }

    #[cfg(feature = "pagination")]
    #[test]
    fn signed_tokens_and_cursors_cannot_be_exchanged_with_a_shared_key() {
        use crate::pagination::{CursorError, SignedCursorCodec};

        let token_codec = SignedTokenCodec::new(KEY).unwrap();
        let cursor_codec = SignedCursorCodec::new(KEY).unwrap();
        let payload = json!({"sub": "usr_01"});
        let cursor = cursor_codec.encode(&payload).unwrap();
        assert_eq!(
            token_codec.decode::<serde_json::Value>(&format!("v2.{cursor}")),
            Err(CryptoError::InvalidSignature)
        );

        // Make the token's JSON a valid cursor envelope: only its purpose differs.
        let token = token_codec
            .encode(&json!({"version": 1, "payload": payload}))
            .unwrap();
        assert!(matches!(
            cursor_codec.decode::<serde_json::Value>(token.strip_prefix("v2.").unwrap()),
            Err(CursorError::InvalidSignature)
        ));
    }

    #[test]
    fn signed_token_round_trips_json_payload() {
        let codec = SignedTokenCodec::new(KEY).expect("valid key");
        let token = codec
            .encode(&json!({ "sub": "usr_01" }))
            .expect("token should encode");
        let decoded: serde_json::Value = codec.decode(&token).expect("token should decode");

        assert_eq!(decoded["sub"], "usr_01");

        let token = codec.encode("usr_01").unwrap();
        assert_eq!(codec.decode::<String>(&token).unwrap(), "usr_01");
        let items: &[u32] = &[1, 2, 3];
        let token = codec.encode(items).unwrap();
        assert_eq!(codec.decode::<Vec<u32>>(&token).unwrap(), items);
    }

    #[test]
    fn signed_token_accepts_previous_key_for_rotation() {
        let old_codec = SignedTokenCodec::new(OLD_KEY).expect("valid key");
        let token = old_codec
            .encode(&json!({ "sub": "usr_01" }))
            .expect("token should encode");

        let rotated = SignedTokenCodec::new(KEY)
            .expect("valid key")
            .with_previous_key(OLD_KEY)
            .expect("valid previous key");
        let decoded: serde_json::Value = rotated.decode(&token).expect("token should decode");

        assert_eq!(decoded["sub"], "usr_01");
    }

    #[test]
    fn signed_token_rejects_tampering() {
        let codec = SignedTokenCodec::new(KEY).expect("valid key");
        let token = codec
            .encode(&json!({ "sub": "usr_01" }))
            .expect("token should encode");
        let mut tampered = token.clone();
        let last = tampered.pop().expect("token should not be empty");
        tampered.push(if last == 'A' { 'B' } else { 'A' });

        assert_eq!(
            codec.decode::<serde_json::Value>(&tampered).unwrap_err(),
            CryptoError::InvalidSignature
        );
    }

    #[test]
    fn signed_token_rejects_invalid_size_limits() {
        assert_eq!(
            SignedTokenCodec::new(KEY)
                .expect("valid key")
                .with_max_token_bytes(0)
                .expect_err("zero max token bytes should fail"),
            CryptoError::InvalidSignedTokenMaxBytes
        );

        let codec = SignedTokenCodec::new(KEY)
            .expect("valid key")
            .with_max_token_bytes(8)
            .expect("limit should be valid");
        assert_eq!(
            codec.encode(&json!({ "sub": "usr_01" })).unwrap_err(),
            CryptoError::TokenTooLarge
        );
    }
}