Skip to main content

zaun_community_protocol/
b64.rs

1//! Strict base64url without padding (specification ยง2).
2//!
3//! Decoding rejects padding, characters outside the URL-safe alphabet and non-canonical
4//! encodings (non-zero trailing bits). Every binary value in JSON goes through here.
5
6use base64::Engine;
7use base64::alphabet::URL_SAFE;
8use base64::engine::{DecodePaddingMode, GeneralPurpose, GeneralPurposeConfig};
9
10const ENGINE: GeneralPurpose = GeneralPurpose::new(
11    &URL_SAFE,
12    GeneralPurposeConfig::new()
13        .with_encode_padding(false)
14        .with_decode_padding_mode(DecodePaddingMode::RequireNone)
15        .with_decode_allow_trailing_bits(false),
16);
17
18/// The input is not canonical base64url without padding.
19#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
20#[error("invalid base64url")]
21pub struct B64Error;
22
23/// Encodes `bytes` as base64url without padding.
24#[must_use]
25pub fn encode(bytes: &[u8]) -> String {
26    ENGINE.encode(bytes)
27}
28
29/// Decodes canonical base64url without padding.
30///
31/// # Errors
32/// [`B64Error`] for padding, a foreign character or non-zero trailing bits.
33pub fn decode(text: &str) -> Result<Vec<u8>, B64Error> {
34    ENGINE.decode(text).map_err(|_| B64Error)
35}
36
37/// Decodes exactly `N` bytes.
38///
39/// # Errors
40/// [`B64Error`] when the text is not canonical or decodes to another length.
41pub fn decode_array<const N: usize>(text: &str) -> Result<[u8; N], B64Error> {
42    // Reject by text length first so an oversized input is not decoded.
43    if text.len() != encoded_len(N) {
44        return Err(B64Error);
45    }
46    decode(text)?.try_into().map_err(|_| B64Error)
47}
48
49/// The length of the unpadded encoding of `n` bytes.
50#[must_use]
51pub const fn encoded_len(n: usize) -> usize {
52    (n * 4).div_ceil(3)
53}
54
55/// `#[serde(with = "crate::b64::bytes")]` for a `Vec<u8>` field.
56pub mod bytes {
57    use serde::{Deserialize, Deserializer, Serializer, de::Error as _};
58
59    /// Serializes as base64url.
60    ///
61    /// # Errors
62    /// Never fails beyond the serializer's own errors.
63    pub fn serialize<S: Serializer>(value: &[u8], s: S) -> Result<S::Ok, S::Error> {
64        s.serialize_str(&super::encode(value))
65    }
66
67    /// Deserializes strict base64url.
68    ///
69    /// # Errors
70    /// A non-canonical encoding.
71    pub fn deserialize<'de, D: Deserializer<'de>>(d: D) -> Result<Vec<u8>, D::Error> {
72        let text = <std::borrow::Cow<'de, str>>::deserialize(d)?;
73        super::decode(&text).map_err(D::Error::custom)
74    }
75}
76
77#[cfg(test)]
78mod tests {
79    use super::*;
80
81    #[test]
82    fn round_trips_and_lengths() {
83        for n in 0..70 {
84            let data: Vec<u8> = (0..n).map(|i| i as u8).collect();
85            let text = encode(&data);
86            assert_eq!(text.len(), encoded_len(n));
87            assert_eq!(decode(&text).unwrap(), data);
88        }
89        assert_eq!(encoded_len(16), 22);
90        assert_eq!(encoded_len(32), 43);
91    }
92
93    #[test]
94    fn rejects_padding_alphabet_and_trailing_bits() {
95        assert_eq!(decode("AA=="), Err(B64Error));
96        assert_eq!(decode("AA+/"), Err(B64Error));
97        // "AB" decodes one byte but leaves non-zero trailing bits.
98        assert_eq!(decode("AB"), Err(B64Error));
99        assert_eq!(decode("AA").unwrap(), vec![0]);
100        assert!(decode_array::<16>("AAAAAAAAAAAAAAAAAAAAAA").is_ok());
101        assert!(decode_array::<16>("AAAAAAAAAAAAAAAAAAAAA").is_err());
102        assert!(decode_array::<16>("AAAAAAAAAAAAAAAAAAAAAAA").is_err());
103    }
104}