entropy-auth 2026.7.31

Authentication and authorization for Entropy Softworks server and API projects
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
//! RFC 4648 Base64 and Base64url encoding/decoding.
//!
//! Implements both the standard Base64 alphabet (Section 4) and the URL-safe
//! alphabet (Section 5) with correct padding semantics. Standard Base64
//! requires padding on encode and decode; Base64url omits padding on encode
//! and tolerates missing padding on decode.

use core::fmt;

// ---------------------------------------------------------------------------
// Alphabet tables
// ---------------------------------------------------------------------------

/// Standard Base64 alphabet (RFC 4648 Table 1).
const STD_ENCODE: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";

/// URL-safe Base64 alphabet (RFC 4648 Table 2).
const URL_ENCODE: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";

/// Decode table for standard Base64. 255 marks invalid positions.
const STD_DECODE: [u8; 256] = build_decode_table(STD_ENCODE);

/// Decode table for URL-safe Base64. 255 marks invalid positions.
const URL_DECODE: [u8; 256] = build_decode_table(URL_ENCODE);

/// Build a 256-byte decode lookup table at compile time.
#[allow(clippy::cast_possible_truncation)]
const fn build_decode_table(alphabet: &[u8; 64]) -> [u8; 256] {
    let mut table = [255u8; 256];
    let mut i = 0;
    while i < 64 {
        table[alphabet[i] as usize] = i as u8;
        i += 1;
    }
    table
}

// ---------------------------------------------------------------------------
// Error type
// ---------------------------------------------------------------------------

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[allow(clippy::enum_variant_names)]
enum Base64DecodeErrorKind {
    /// Input contains a character not in the Base64 alphabet.
    InvalidCharacter,
    /// Padding is incorrect (wrong position, wrong count, or missing when required).
    InvalidPadding,
    /// Input length is not valid (not a multiple of 4 for standard, or remainder 1 for url-safe).
    InvalidLength,
    /// The final quantum has non-zero bits that a canonical encoder would
    /// have left zero (RFC 4648 Section 3.5). Rejected to keep decoding
    /// bijective — distinct inputs must not decode to identical bytes.
    NonCanonical,
}

/// Error returned when Base64 decoding fails.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Base64DecodeError {
    kind: Base64DecodeErrorKind,
}

impl Base64DecodeError {
    const fn new(kind: Base64DecodeErrorKind) -> Self {
        Self { kind }
    }
}

impl fmt::Display for Base64DecodeError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self.kind {
            Base64DecodeErrorKind::InvalidCharacter => {
                write!(f, "base64: invalid character in input")
            }
            Base64DecodeErrorKind::InvalidPadding => {
                write!(f, "base64: invalid padding")
            }
            Base64DecodeErrorKind::InvalidLength => {
                write!(f, "base64: invalid input length")
            }
            Base64DecodeErrorKind::NonCanonical => {
                write!(f, "base64: non-canonical encoding (non-zero trailing bits)")
            }
        }
    }
}

impl std::error::Error for Base64DecodeError {}

// ---------------------------------------------------------------------------
// Encoding
// ---------------------------------------------------------------------------

/// Encode bytes to standard Base64 with `=` padding (RFC 4648 Section 4).
///
/// # Examples
///
/// ```
/// use entropy_auth::base64_encode;
///
/// assert_eq!(base64_encode(b"foo"), "Zm9v");
/// assert_eq!(base64_encode(b"foob"), "Zm9vYg==");
/// ```
#[must_use]
pub fn base64_encode(input: &[u8]) -> String {
    encode_with_alphabet(input, STD_ENCODE, true)
}

/// Encode bytes to URL-safe Base64 **without** padding (RFC 4648 Section 5).
///
/// # Examples
///
/// ```
/// use entropy_auth::base64url_encode;
///
/// // URL-safe alphabet and no trailing padding.
/// assert_eq!(base64url_encode(b"foob"), "Zm9vYg");
/// ```
#[must_use]
pub fn base64url_encode(input: &[u8]) -> String {
    encode_with_alphabet(input, URL_ENCODE, false)
}

fn encode_with_alphabet(input: &[u8], alphabet: &[u8; 64], pad: bool) -> String {
    if input.is_empty() {
        return String::new();
    }

    // Every 3 input bytes produce 4 output characters.
    let full_chunks = input.len() / 3;
    let remainder = input.len() % 3;
    let capacity = if pad {
        (full_chunks + usize::from(remainder > 0)) * 4
    } else {
        full_chunks * 4
            + match remainder {
                1 => 2,
                2 => 3,
                _ => 0,
            }
    };

    let mut out = Vec::with_capacity(capacity);
    let chunks = input.chunks_exact(3);
    let tail = chunks.remainder();

    for chunk in chunks {
        let n = (u32::from(chunk[0]) << 16) | (u32::from(chunk[1]) << 8) | u32::from(chunk[2]);
        out.push(alphabet[((n >> 18) & 0x3F) as usize]);
        out.push(alphabet[((n >> 12) & 0x3F) as usize]);
        out.push(alphabet[((n >> 6) & 0x3F) as usize]);
        out.push(alphabet[(n & 0x3F) as usize]);
    }

    match tail.len() {
        1 => {
            let n = u32::from(tail[0]) << 16;
            out.push(alphabet[((n >> 18) & 0x3F) as usize]);
            out.push(alphabet[((n >> 12) & 0x3F) as usize]);
            if pad {
                out.push(b'=');
                out.push(b'=');
            }
        }
        2 => {
            let n = (u32::from(tail[0]) << 16) | (u32::from(tail[1]) << 8);
            out.push(alphabet[((n >> 18) & 0x3F) as usize]);
            out.push(alphabet[((n >> 12) & 0x3F) as usize]);
            out.push(alphabet[((n >> 6) & 0x3F) as usize]);
            if pad {
                out.push(b'=');
            }
        }
        _ => {}
    }

    // `out` consists entirely of ASCII characters from the alphabet and '=',
    // so `from_utf8` cannot fail; the checked conversion keeps us within the
    // crate's `deny(unsafe_code)` policy (no `from_utf8_unchecked`).
    #[allow(clippy::expect_used)]
    String::from_utf8(out).expect("base64 output is always valid ASCII")
}

// ---------------------------------------------------------------------------
// Decoding
// ---------------------------------------------------------------------------

/// Decode a standard Base64 string (RFC 4648 Section 4).
///
/// Padding (`=`) is **required**.
///
/// # Security
///
/// Decoding is **not** constant-time — it branches on each input symbol.
/// Decoded secret material must be compared with
/// [`constant_time_eq`](crate::constant_time_eq), never `==`.
///
/// # Errors
///
/// Returns [`Base64DecodeError`] if the input contains invalid characters,
/// has incorrect padding, has an invalid length, or is a non-canonical
/// encoding (non-zero trailing bits in the final group, RFC 4648 §3.5).
///
/// # Examples
///
/// ```
/// use entropy_auth::base64_decode;
///
/// assert_eq!(base64_decode("Zm9v").unwrap(), b"foo");
/// // Non-canonical trailing bits are rejected.
/// assert!(base64_decode("Zm9vYh==").is_err());
/// ```
pub fn base64_decode(input: &str) -> Result<Vec<u8>, Base64DecodeError> {
    decode_impl(input.as_bytes(), &STD_DECODE, true)
}

/// Decode a URL-safe Base64 string (RFC 4648 Section 5).
///
/// Padding is tolerated but not required.
///
/// # Security
///
/// Decoding is **not** constant-time — it branches on each input symbol.
/// Decoded secret material must be compared with
/// [`constant_time_eq`](crate::constant_time_eq), never `==`.
///
/// # Errors
///
/// Returns [`Base64DecodeError`] if the input contains invalid characters,
/// has incorrect padding, has an invalid length, or is a non-canonical
/// encoding (non-zero trailing bits in the final group, RFC 4648 §3.5).
///
/// # Examples
///
/// ```
/// use entropy_auth::base64url_decode;
///
/// assert_eq!(base64url_decode("Zm9vYg").unwrap(), b"foob");
/// ```
pub fn base64url_decode(input: &str) -> Result<Vec<u8>, Base64DecodeError> {
    decode_impl(input.as_bytes(), &URL_DECODE, false)
}

#[allow(clippy::many_single_char_names, clippy::cast_possible_truncation)]
fn decode_impl(
    input: &[u8],
    decode_table: &[u8; 256],
    require_padding: bool,
) -> Result<Vec<u8>, Base64DecodeError> {
    if input.is_empty() {
        return Ok(Vec::new());
    }

    // Strip trailing padding.
    let pad_count = input.iter().rev().take_while(|&&b| b == b'=').count();
    if pad_count > 2 {
        return Err(Base64DecodeError::new(
            Base64DecodeErrorKind::InvalidPadding,
        ));
    }

    let data = &input[..input.len() - pad_count];

    // Validate lengths.
    if require_padding {
        // With padding the total length must be a multiple of 4.
        if input.len() % 4 != 0 {
            return Err(Base64DecodeError::new(Base64DecodeErrorKind::InvalidLength));
        }
    } else {
        // Without padding, remainder of 1 is never valid (you can't encode
        // partial bits that way).
        if data.len() % 4 == 1 {
            return Err(Base64DecodeError::new(Base64DecodeErrorKind::InvalidLength));
        }
    }

    // Validate that padding count is consistent with data length.
    let expected_pad = match data.len() % 4 {
        0 => 0,
        2 => 2,
        3 => 1,
        _ => return Err(Base64DecodeError::new(Base64DecodeErrorKind::InvalidLength)),
    };

    // Standard base64 requires exactly `expected_pad` padding bytes. Url-safe
    // padding is optional, but when present it must be correct — a stray pad
    // (e.g. "Zg=" instead of "Zg" or "Zg==") is rejected so each byte string
    // has exactly one accepted encoding.
    let padding_ok = if require_padding {
        pad_count == expected_pad
    } else {
        pad_count == 0 || pad_count == expected_pad
    };
    if !padding_ok {
        return Err(Base64DecodeError::new(
            Base64DecodeErrorKind::InvalidPadding,
        ));
    }

    // Decode.
    let out_len = data.len() * 3 / 4;
    let mut out = Vec::with_capacity(out_len);

    let chunks = data.chunks_exact(4);
    let tail = chunks.remainder();

    for chunk in chunks {
        let a = decode_char(chunk[0], decode_table)?;
        let b = decode_char(chunk[1], decode_table)?;
        let c = decode_char(chunk[2], decode_table)?;
        let d = decode_char(chunk[3], decode_table)?;

        let n = (u32::from(a) << 18) | (u32::from(b) << 12) | (u32::from(c) << 6) | u32::from(d);
        out.push((n >> 16) as u8);
        out.push((n >> 8) as u8);
        out.push(n as u8);
    }

    match tail.len() {
        2 => {
            let a = decode_char(tail[0], decode_table)?;
            let b = decode_char(tail[1], decode_table)?;
            // Only the top 2 bits of `b` reach the output byte; the low 4
            // must be zero in a canonical encoding.
            if b & 0b0000_1111 != 0 {
                return Err(Base64DecodeError::new(Base64DecodeErrorKind::NonCanonical));
            }
            let n = (u32::from(a) << 18) | (u32::from(b) << 12);
            out.push((n >> 16) as u8);
        }
        3 => {
            let a = decode_char(tail[0], decode_table)?;
            let b = decode_char(tail[1], decode_table)?;
            let c = decode_char(tail[2], decode_table)?;
            // Only the top 4 bits of `c` reach the output; the low 2 must
            // be zero in a canonical encoding.
            if c & 0b0000_0011 != 0 {
                return Err(Base64DecodeError::new(Base64DecodeErrorKind::NonCanonical));
            }
            let n = (u32::from(a) << 18) | (u32::from(b) << 12) | (u32::from(c) << 6);
            out.push((n >> 16) as u8);
            out.push((n >> 8) as u8);
        }
        _ => {}
    }

    Ok(out)
}

/// Resolve a single Base64 character to its 6-bit value.
#[inline]
fn decode_char(byte: u8, table: &[u8; 256]) -> Result<u8, Base64DecodeError> {
    let val = table[byte as usize];
    if val == 255 {
        return Err(Base64DecodeError::new(
            Base64DecodeErrorKind::InvalidCharacter,
        ));
    }
    Ok(val)
}

// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------

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

    // --- RFC 4648 Section 10 test vectors (standard Base64) ---

    #[test]
    fn encode_empty() {
        assert_eq!(base64_encode(b""), "");
    }

    #[test]
    fn encode_f() {
        assert_eq!(base64_encode(b"f"), "Zg==");
    }

    #[test]
    fn encode_fo() {
        assert_eq!(base64_encode(b"fo"), "Zm8=");
    }

    #[test]
    fn encode_foo() {
        assert_eq!(base64_encode(b"foo"), "Zm9v");
    }

    #[test]
    fn encode_foob() {
        assert_eq!(base64_encode(b"foob"), "Zm9vYg==");
    }

    #[test]
    fn encode_fooba() {
        assert_eq!(base64_encode(b"fooba"), "Zm9vYmE=");
    }

    #[test]
    fn encode_foobar() {
        assert_eq!(base64_encode(b"foobar"), "Zm9vYmFy");
    }

    // --- Standard Base64 decode (RFC 4648 Section 10) ---

    #[test]
    fn decode_empty() {
        assert_eq!(base64_decode("").unwrap(), b"");
    }

    #[test]
    fn decode_f() {
        assert_eq!(base64_decode("Zg==").unwrap(), b"f");
    }

    #[test]
    fn decode_fo() {
        assert_eq!(base64_decode("Zm8=").unwrap(), b"fo");
    }

    #[test]
    fn decode_foo() {
        assert_eq!(base64_decode("Zm9v").unwrap(), b"foo");
    }

    #[test]
    fn decode_foob() {
        assert_eq!(base64_decode("Zm9vYg==").unwrap(), b"foob");
    }

    #[test]
    fn decode_fooba() {
        assert_eq!(base64_decode("Zm9vYmE=").unwrap(), b"fooba");
    }

    #[test]
    fn decode_foobar() {
        assert_eq!(base64_decode("Zm9vYmFy").unwrap(), b"foobar");
    }

    // --- Standard Base64 round-trip ---

    #[test]
    fn standard_round_trip_binary() {
        let data: Vec<u8> = (0..=255).collect();
        let encoded = base64_encode(&data);
        let decoded = base64_decode(&encoded).unwrap();
        assert_eq!(decoded, data);
    }

    #[test]
    fn standard_round_trip_short_lengths() {
        for len in 0..=32_u8 {
            let data: Vec<u8> = (0..len).collect();
            let encoded = base64_encode(&data);
            let decoded = base64_decode(&encoded).unwrap();
            assert_eq!(decoded, data, "round-trip failed for length {len}");
        }
    }

    // --- Standard Base64 error cases ---

    #[test]
    fn decode_rejects_invalid_character() {
        let err = base64_decode("Zm9!").unwrap_err();
        assert_eq!(
            err,
            Base64DecodeError::new(Base64DecodeErrorKind::InvalidCharacter)
        );
    }

    #[test]
    fn decode_rejects_invalid_length() {
        // Length 5 is not a valid padded Base64 length.
        let err = base64_decode("AAAAA").unwrap_err();
        assert_eq!(
            err,
            Base64DecodeError::new(Base64DecodeErrorKind::InvalidLength)
        );
    }

    #[test]
    fn decode_rejects_missing_padding() {
        // Standard Base64 requires padding.
        let err = base64_decode("Zg").unwrap_err();
        assert_eq!(
            err,
            Base64DecodeError::new(Base64DecodeErrorKind::InvalidLength)
        );
    }

    #[test]
    fn decode_rejects_wrong_padding_count() {
        // "Zm9v" encodes "foo" — 3 bytes, no padding needed.
        // Adding padding where none belongs is invalid.
        let err = base64_decode("Zm9v=").unwrap_err();
        assert_eq!(
            err,
            Base64DecodeError::new(Base64DecodeErrorKind::InvalidLength)
        );
    }

    #[test]
    fn decode_rejects_triple_padding() {
        let err = base64_decode("Z===").unwrap_err();
        assert_eq!(
            err,
            Base64DecodeError::new(Base64DecodeErrorKind::InvalidPadding)
        );
    }

    #[test]
    fn decode_rejects_interior_padding() {
        // Only *trailing* `=` are stripped; an `=` in the middle of the
        // data is a classic non-canonical / parser-differential vector and
        // must be rejected as an invalid character, not silently accepted.
        let err = base64_decode("Z=g=").unwrap_err();
        assert_eq!(
            err,
            Base64DecodeError::new(Base64DecodeErrorKind::InvalidCharacter)
        );
    }

    // --- Base64url encode (RFC 4648 Section 5) ---

    #[test]
    fn url_encode_empty() {
        assert_eq!(base64url_encode(b""), "");
    }

    #[test]
    fn url_encode_f() {
        // No padding for url-safe.
        assert_eq!(base64url_encode(b"f"), "Zg");
    }

    #[test]
    fn url_encode_fo() {
        assert_eq!(base64url_encode(b"fo"), "Zm8");
    }

    #[test]
    fn url_encode_foo() {
        assert_eq!(base64url_encode(b"foo"), "Zm9v");
    }

    #[test]
    fn url_encode_foob() {
        assert_eq!(base64url_encode(b"foob"), "Zm9vYg");
    }

    #[test]
    fn url_encode_fooba() {
        assert_eq!(base64url_encode(b"fooba"), "Zm9vYmE");
    }

    #[test]
    fn url_encode_foobar() {
        assert_eq!(base64url_encode(b"foobar"), "Zm9vYmFy");
    }

    #[test]
    fn url_encode_uses_url_safe_alphabet() {
        // Bytes that produce `+` and `/` in standard should produce `-` and `_`.
        let input: &[u8] = &[0xFB, 0xFF, 0xFE];
        let standard = base64_encode(input);
        let url_safe = base64url_encode(input);
        assert!(standard.contains('+') || standard.contains('/'));
        assert!(!url_safe.contains('+'));
        assert!(!url_safe.contains('/'));
    }

    // --- Base64url decode ---

    #[test]
    fn url_decode_empty() {
        assert_eq!(base64url_decode("").unwrap(), b"");
    }

    #[test]
    fn url_decode_no_padding() {
        assert_eq!(base64url_decode("Zg").unwrap(), b"f");
        assert_eq!(base64url_decode("Zm8").unwrap(), b"fo");
    }

    #[test]
    fn url_decode_with_optional_padding() {
        assert_eq!(base64url_decode("Zg==").unwrap(), b"f");
        assert_eq!(base64url_decode("Zm8=").unwrap(), b"fo");
    }

    #[test]
    fn url_round_trip_binary() {
        let data: Vec<u8> = (0..=255).collect();
        let encoded = base64url_encode(&data);
        let decoded = base64url_decode(&encoded).unwrap();
        assert_eq!(decoded, data);
    }

    #[test]
    fn url_round_trip_short_lengths() {
        for len in 0..=32_u8 {
            let data: Vec<u8> = (0..len).collect();
            let encoded = base64url_encode(&data);
            let decoded = base64url_decode(&encoded).unwrap();
            assert_eq!(decoded, data, "url round-trip failed for length {len}");
        }
    }

    #[test]
    fn url_decode_rejects_invalid_character() {
        let err = base64url_decode("Zm9v!!!").unwrap_err();
        assert_eq!(
            err,
            Base64DecodeError::new(Base64DecodeErrorKind::InvalidCharacter)
        );
    }

    #[test]
    fn url_decode_rejects_standard_alphabet_chars() {
        // `+` and `/` are not valid in URL-safe Base64.
        assert!(base64url_decode("ab+c").is_err());
        assert!(base64url_decode("ab/c").is_err());
    }

    #[test]
    fn url_decode_rejects_invalid_length() {
        // A single character can never be valid (remainder 1 mod 4).
        let err = base64url_decode("A").unwrap_err();
        assert_eq!(
            err,
            Base64DecodeError::new(Base64DecodeErrorKind::InvalidLength)
        );
    }

    // --- Display ---

    #[test]
    fn error_display_messages() {
        let invalid_char = Base64DecodeError::new(Base64DecodeErrorKind::InvalidCharacter);
        assert_eq!(
            invalid_char.to_string(),
            "base64: invalid character in input"
        );

        let invalid_pad = Base64DecodeError::new(Base64DecodeErrorKind::InvalidPadding);
        assert_eq!(invalid_pad.to_string(), "base64: invalid padding");

        let invalid_len = Base64DecodeError::new(Base64DecodeErrorKind::InvalidLength);
        assert_eq!(invalid_len.to_string(), "base64: invalid input length");
    }

    #[test]
    fn error_implements_std_error() {
        let err: Box<dyn std::error::Error> = Box::new(Base64DecodeError::new(
            Base64DecodeErrorKind::InvalidCharacter,
        ));
        // Just verify it compiles and we can call Display through the trait object.
        let _ = err.to_string();
    }

    #[test]
    fn decode_rejects_non_canonical_trailing_bits() {
        // "Zg==" is the canonical encoding of `f`. "Zh==" decodes to the
        // same byte but sets discarded low bits — reject it so decoding is
        // bijective (no two strings decode to one byte string).
        assert_eq!(base64_decode("Zg==").unwrap(), b"f");
        let err = base64_decode("Zh==").unwrap_err();
        assert_eq!(
            err,
            Base64DecodeError::new(Base64DecodeErrorKind::NonCanonical)
        );

        // 3-char tail: "Zm8=" is canonical for "fo"; "Zm9=" sets the
        // discarded low 2 bits of the final sextet.
        assert_eq!(base64_decode("Zm8=").unwrap(), b"fo");
        let err = base64_decode("Zm9=").unwrap_err();
        assert_eq!(
            err,
            Base64DecodeError::new(Base64DecodeErrorKind::NonCanonical)
        );

        // Same property holds on the url-safe (unpadded) path.
        assert_eq!(base64url_decode("Zg").unwrap(), b"f");
        let err = base64url_decode("Zh").unwrap_err();
        assert_eq!(
            err,
            Base64DecodeError::new(Base64DecodeErrorKind::NonCanonical)
        );
    }

    #[test]
    fn encoder_output_always_round_trips() {
        // Property: the crate's own (canonical) encoder output must always
        // decode back, for every input length / final-quantum shape. This
        // guards against the non-canonical check ever rejecting conforming
        // encodings (e.g. fixed-length JWS signatures, RSA JWK moduli).
        for len in 0..=130usize {
            let bytes: Vec<u8> = (0..len)
                .map(|i| u8::try_from((i * 31 + 7) % 256).unwrap())
                .collect();
            let std = base64_encode(&bytes);
            assert_eq!(base64_decode(&std).unwrap(), bytes, "std len {len}");
            let url = base64url_encode(&bytes);
            assert_eq!(base64url_decode(&url).unwrap(), bytes, "url len {len}");
        }
    }

    #[test]
    fn decode_url_rejects_stray_padding() {
        // url-safe tolerates absent padding, but a present-yet-wrong pad
        // count ("Zg=" instead of "Zg" or "Zg==") is rejected.
        assert_eq!(base64url_decode("Zg").unwrap(), b"f");
        let err = base64url_decode("Zg=").unwrap_err();
        assert_eq!(
            err,
            Base64DecodeError::new(Base64DecodeErrorKind::InvalidPadding)
        );
    }
}