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
//! RFC 4648 Section 6 Base32 encoding/decoding.
//!
//! Implements the standard Base32 alphabet (A–Z, 2–7) with `=` padding on
//! encode. Decoding is case-insensitive and accepts either fully-padded or
//! unpadded input; partially/incorrectly padded input is rejected so a value
//! has at most one padded and one unpadded spelling.

use core::fmt;

// ---------------------------------------------------------------------------
// Alphabet table
// ---------------------------------------------------------------------------

/// Standard Base32 alphabet (RFC 4648 Table 3).
const BASE32_ALPHABET: &[u8; 32] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567";

/// Decode table: maps ASCII byte value to its 5-bit value.
/// 255 marks invalid positions.
const BASE32_DECODE: [u8; 256] = build_decode_table();

/// Build a 256-byte decode lookup table at compile time.
/// Case-insensitive: both uppercase and lowercase letters map to the same value.
#[allow(clippy::cast_possible_truncation)]
const fn build_decode_table() -> [u8; 256] {
    let mut table = [255u8; 256];
    let mut i = 0u8;
    while i < 32 {
        let ch = BASE32_ALPHABET[i as usize];
        table[ch as usize] = i;
        // Also map lowercase equivalent for A-Z.
        if ch >= b'A' && ch <= b'Z' {
            table[(ch + 32) as usize] = i;
        }
        i += 1;
    }
    table
}

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

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Base32DecodeErrorKind {
    /// Input contains a character not in the Base32 alphabet.
    InvalidCharacter,
    /// Input length (after stripping padding) is not valid.
    InvalidLength,
    /// The final group has non-zero trailing bits that a canonical encoder
    /// would have left zero (RFC 4648 Section 3.5). Rejected to keep
    /// decoding bijective.
    NonCanonical,
}

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

impl Base32DecodeError {
    const fn new(kind: Base32DecodeErrorKind) -> Self {
        Self { kind }
    }
}

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

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

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

/// Encode bytes to standard Base32 with `=` padding (RFC 4648 Section 6).
///
/// # Examples
///
/// ```
/// use entropy_auth::encoding::base32_encode;
///
/// assert_eq!(base32_encode(b"foo"), "MZXW6===");
/// ```
#[must_use]
#[allow(clippy::missing_panics_doc)]
pub fn base32_encode(input: &[u8]) -> String {
    if input.is_empty() {
        return String::new();
    }

    // Every 5 input bytes produce 8 output characters.
    let full_chunks = input.len() / 5;
    let remainder = input.len() % 5;
    let capacity = (full_chunks + usize::from(remainder > 0)) * 8;

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

    for chunk in chunks {
        // Combine 5 bytes into a 40-bit value.
        let n: u64 = (u64::from(chunk[0]) << 32)
            | (u64::from(chunk[1]) << 24)
            | (u64::from(chunk[2]) << 16)
            | (u64::from(chunk[3]) << 8)
            | u64::from(chunk[4]);

        out.push(BASE32_ALPHABET[((n >> 35) & 0x1F) as usize]);
        out.push(BASE32_ALPHABET[((n >> 30) & 0x1F) as usize]);
        out.push(BASE32_ALPHABET[((n >> 25) & 0x1F) as usize]);
        out.push(BASE32_ALPHABET[((n >> 20) & 0x1F) as usize]);
        out.push(BASE32_ALPHABET[((n >> 15) & 0x1F) as usize]);
        out.push(BASE32_ALPHABET[((n >> 10) & 0x1F) as usize]);
        out.push(BASE32_ALPHABET[((n >> 5) & 0x1F) as usize]);
        out.push(BASE32_ALPHABET[(n & 0x1F) as usize]);
    }

    // Handle the remaining bytes with appropriate padding.
    if !tail.is_empty() {
        // Pad the tail to 5 bytes for uniform processing.
        let mut buf = [0u8; 5];
        buf[..tail.len()].copy_from_slice(tail);
        let n: u64 = (u64::from(buf[0]) << 32)
            | (u64::from(buf[1]) << 24)
            | (u64::from(buf[2]) << 16)
            | (u64::from(buf[3]) << 8)
            | u64::from(buf[4]);

        // Number of meaningful output chars and padding chars:
        // 1 byte  -> 2 chars + 6 pad
        // 2 bytes -> 4 chars + 4 pad
        // 3 bytes -> 5 chars + 3 pad
        // 4 bytes -> 7 chars + 1 pad
        let (chars, pad) = match tail.len() {
            1 => (2, 6),
            2 => (4, 4),
            3 => (5, 3),
            4 => (7, 1),
            _ => unreachable!(),
        };

        let shifts = [35, 30, 25, 20, 15, 10, 5, 0];
        for &shift in &shifts[..chars] {
            out.push(BASE32_ALPHABET[((n >> shift) & 0x1F) as usize]);
        }
        out.extend(std::iter::repeat_n(b'=', pad));
    }

    // NOTE: output consists entirely of ASCII characters from the alphabet
    // and '=', so from_utf8 cannot fail in practice.
    #[allow(clippy::expect_used)]
    String::from_utf8(out).expect("base32 output is always valid ASCII")
}

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

/// Decode a standard Base32 string (RFC 4648 Section 6).
///
/// Decoding is case-insensitive. Trailing `=` padding is stripped before
/// processing.
///
/// # Security
///
/// Decoding is **not** constant-time — it branches on each input symbol. It
/// is safe for decoding stored/encoded secrets (e.g. a TOTP shared secret),
/// but the decoded bytes must be compared with
/// [`constant_time_eq`](crate::constant_time_eq), never `==`.
///
/// # Errors
///
/// Returns [`Base32DecodeError`] if the input contains invalid characters
/// or has an invalid length.
///
/// # Examples
///
/// ```
/// use entropy_auth::encoding::base32_decode;
///
/// assert_eq!(base32_decode("MZXW6===").unwrap(), b"foo");
/// ```
#[allow(clippy::cast_possible_truncation)]
pub fn base32_decode(input: &str) -> Result<Vec<u8>, Base32DecodeError> {
    if input.is_empty() {
        return Ok(Vec::new());
    }

    let input = input.as_bytes();

    // Strip trailing padding.
    let pad_count = input.iter().rev().take_while(|&&b| b == b'=').count();
    let data = &input[..input.len() - pad_count];

    if data.is_empty() {
        return Err(Base32DecodeError::new(Base32DecodeErrorKind::InvalidLength));
    }

    // Valid remainder lengths after stripping padding: 0, 2, 4, 5, 7
    // (corresponding to 0, 1, 2, 3, 4 output bytes from the last group).
    // Remainder 1, 3, 6 are invalid.
    let rem = data.len() % 8;
    if rem == 1 || rem == 3 || rem == 6 {
        return Err(Base32DecodeError::new(Base32DecodeErrorKind::InvalidLength));
    }

    // Unpadded input is accepted (the common form for TOTP secrets), but if any
    // padding is present it must be canonical: the exact count RFC 4648 requires
    // for this remainder. Otherwise "MY", "MY=", "MY==" … "MY======" would all
    // decode to the same bytes, so the padding carries no information and many
    // distinct strings map to one value.
    if pad_count > 0 {
        let expected_pad = (8 - rem) % 8;
        if pad_count != expected_pad {
            return Err(Base32DecodeError::new(Base32DecodeErrorKind::InvalidLength));
        }
    }

    // Calculate output length.
    let full_groups = data.len() / 8;
    let out_len = full_groups * 5
        + match rem {
            2 => 1,
            4 => 2,
            5 => 3,
            7 => 4,
            _ => 0,
        };

    let mut out = Vec::with_capacity(out_len);

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

    for chunk in chunks {
        let mut n: u64 = 0;
        for &byte in chunk {
            let val = decode_char(byte)?;
            n = (n << 5) | u64::from(val);
        }
        out.push((n >> 32) as u8);
        out.push((n >> 24) as u8);
        out.push((n >> 16) as u8);
        out.push((n >> 8) as u8);
        out.push(n as u8);
    }

    if !tail.is_empty() {
        let mut n: u64 = 0;
        for &byte in tail {
            let val = decode_char(byte)?;
            n = (n << 5) | u64::from(val);
        }
        // Shift left to align the bits to the top of the 40-bit space.
        let shift = (8 - tail.len()) * 5;
        n <<= shift;

        let bytes_out = match tail.len() {
            2 => 1,
            4 => 2,
            5 => 3,
            7 => 4,
            _ => return Err(Base32DecodeError::new(Base32DecodeErrorKind::InvalidLength)),
        };

        // The emitted bytes occupy the top `bytes_out * 8` bits of the
        // 40-bit group; the remaining low bits carry no output and must be
        // zero in a canonical encoding.
        let residual_mask = (1u64 << (40 - bytes_out * 8)) - 1;
        if n & residual_mask != 0 {
            return Err(Base32DecodeError::new(Base32DecodeErrorKind::NonCanonical));
        }

        let all_bytes = [
            (n >> 32) as u8,
            (n >> 24) as u8,
            (n >> 16) as u8,
            (n >> 8) as u8,
            n as u8,
        ];
        out.extend_from_slice(&all_bytes[..bytes_out]);
    }

    Ok(out)
}

/// Resolve a single Base32 character to its 5-bit value.
#[inline]
fn decode_char(byte: u8) -> Result<u8, Base32DecodeError> {
    let val = BASE32_DECODE[byte as usize];
    if val == 255 {
        return Err(Base32DecodeError::new(
            Base32DecodeErrorKind::InvalidCharacter,
        ));
    }
    Ok(val)
}

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

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

    // --- RFC 4648 Section 10 test vectors ---

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

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

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

    #[test]
    fn encode_foo() {
        assert_eq!(base32_encode(b"foo"), "MZXW6===");
    }

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

    #[test]
    fn encode_fooba() {
        assert_eq!(base32_encode(b"fooba"), "MZXW6YTB");
    }

    #[test]
    fn encode_foobar() {
        assert_eq!(base32_encode(b"foobar"), "MZXW6YTBOI======");
    }

    // --- Decode RFC 4648 test vectors ---

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

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

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

    #[test]
    fn decode_foo() {
        assert_eq!(base32_decode("MZXW6===").unwrap(), b"foo");
    }

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

    #[test]
    fn decode_fooba() {
        assert_eq!(base32_decode("MZXW6YTB").unwrap(), b"fooba");
    }

    #[test]
    fn decode_foobar() {
        assert_eq!(base32_decode("MZXW6YTBOI======").unwrap(), b"foobar");
    }

    // --- Round-trip tests ---

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

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

    // --- Case-insensitive decode ---

    #[test]
    fn decode_case_insensitive() {
        assert_eq!(base32_decode("mzxw6===").unwrap(), b"foo");
        assert_eq!(base32_decode("Mzxw6===").unwrap(), b"foo");
        assert_eq!(base32_decode("mZXW6===").unwrap(), b"foo");
    }

    // --- Decode without padding ---

    #[test]
    fn decode_no_padding() {
        assert_eq!(base32_decode("MY").unwrap(), b"f");
        assert_eq!(base32_decode("MZXQ").unwrap(), b"fo");
        assert_eq!(base32_decode("MZXW6").unwrap(), b"foo");
        assert_eq!(base32_decode("MZXW6YQ").unwrap(), b"foob");
        assert_eq!(base32_decode("MZXW6YTB").unwrap(), b"fooba");
    }

    // --- Error cases ---

    #[test]
    fn decode_rejects_invalid_character() {
        let err = base32_decode("MZ!W6===").unwrap_err();
        assert_eq!(
            err,
            Base32DecodeError::new(Base32DecodeErrorKind::InvalidCharacter)
        );
    }

    #[test]
    fn decode_rejects_digit_0() {
        // '0' and '1' are not in the Base32 alphabet.
        assert!(base32_decode("M0======").is_err());
        assert!(base32_decode("M1======").is_err());
    }

    #[test]
    fn decode_rejects_invalid_length() {
        // Remainder 1 after stripping padding is never valid.
        let err = base32_decode("A").unwrap_err();
        assert_eq!(
            err,
            Base32DecodeError::new(Base32DecodeErrorKind::InvalidLength)
        );
    }

    #[test]
    fn decode_rejects_wrong_padding_count() {
        // "MY======" (6 pad) and "MY" (unpadded) are the only two accepted
        // spellings of `f`; any other pad count is non-canonical.
        assert_eq!(base32_decode("MY======").unwrap(), b"f");
        assert_eq!(base32_decode("MY").unwrap(), b"f");
        for bad in ["MY=", "MY==", "MY===", "MY====", "MY=====", "MY======="] {
            assert!(base32_decode(bad).is_err(), "expected reject: {bad}");
        }
        // A complete group carrying trailing padding is also non-canonical.
        assert!(base32_decode("MZXW6YTB=").is_err());
    }

    #[test]
    fn decode_rejects_all_padding() {
        // A full block of padding strips to an empty data section, which is an
        // invalid (zero-group) encoding rather than the empty string.
        let err = base32_decode("========").unwrap_err();
        assert_eq!(
            err,
            Base32DecodeError::new(Base32DecodeErrorKind::InvalidLength)
        );
    }

    #[test]
    fn encoder_output_always_round_trips() {
        // Property: canonical encoder output must always decode back, for
        // every input length / final-group shape — the non-canonical check
        // must never reject a conforming encoding (e.g. an imported TOTP
        // secret produced by a standard Base32 encoder).
        for len in 0..=130usize {
            let bytes: Vec<u8> = (0..len)
                .map(|i| u8::try_from((i * 31 + 7) % 256).unwrap())
                .collect();
            let encoded = base32_encode(&bytes);
            assert_eq!(base32_decode(&encoded).unwrap(), bytes, "len {len}");
        }
    }

    #[test]
    fn decode_rejects_non_canonical_trailing_bits() {
        // "MY" is the canonical Base32 for `f`. "MZ" decodes to the same
        // byte but sets the discarded low bits of the final group — reject
        // it so decoding stays bijective (relevant for Base32 TOTP secrets).
        assert_eq!(base32_decode("MY").unwrap(), b"f");
        let err = base32_decode("MZ").unwrap_err();
        assert_eq!(
            err,
            Base32DecodeError::new(Base32DecodeErrorKind::NonCanonical)
        );
    }

    // --- Display ---

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

        let invalid_len = Base32DecodeError::new(Base32DecodeErrorKind::InvalidLength);
        assert_eq!(invalid_len.to_string(), "base32: invalid input length");
    }

    #[test]
    fn error_implements_std_error() {
        let err: Box<dyn std::error::Error> = Box::new(Base32DecodeError::new(
            Base32DecodeErrorKind::InvalidCharacter,
        ));
        let _ = err.to_string();
    }
}