mirror of
https://github.com/storytold/craft-libs.git
synced 2026-11-16 23:24:24 +00:00
Merge pull request #1583 from storytold/feat/mime-optional-base64-padding
mime: expose optional Base64 padding without relaxing strict decoding
This commit is contained in:
@@ -8,8 +8,9 @@
|
||||
//! counts it; an unpadded one refuses `=`), a length that can be, and the unused bits of the last
|
||||
//! symbol zero (so every value has one spelling). A caller that reads mail, where line breaks and
|
||||
//! missing padding are everyday, cleans its input first, as it always has; the strictness is what
|
||||
//! the signature, key and credential checks want. No input panics, and the output is never longer
|
||||
//! than three quarters of the input.
|
||||
//! the signature, key and credential checks want. [`Config::decode_optional_padding`] explicitly
|
||||
//! permits missing terminal padding without relaxing alphabet, padding placement or unused bits.
|
||||
//! No input panics, and the output is never longer than three quarters of the input.
|
||||
|
||||
use std::fmt;
|
||||
|
||||
@@ -108,9 +109,20 @@ impl Config {
|
||||
|
||||
/// The bytes of `text`, which must be exactly base64 of this config's kind (see the module).
|
||||
pub fn decode(self, text: impl AsRef<[u8]>) -> Result<Vec<u8>, DecodeError> {
|
||||
let text = text.as_ref();
|
||||
let (symbols, pad) = if self.padded {
|
||||
if text.len() % 4 != 0 {
|
||||
self.decode_inner(text.as_ref(), false)
|
||||
}
|
||||
|
||||
/// Decode this alphabet with zero, partial or complete terminal padding, regardless of the
|
||||
/// config's encoding padding. Whitespace, junk, internal/excess padding and nonzero unused
|
||||
/// bits still fail. Use this only when the calling format permits missing padding; [`Self::decode`]
|
||||
/// remains strict for signatures and credentials that require one spelling.
|
||||
pub fn decode_optional_padding(self, text: impl AsRef<[u8]>) -> Result<Vec<u8>, DecodeError> {
|
||||
self.decode_inner(text.as_ref(), true)
|
||||
}
|
||||
|
||||
fn decode_inner(self, text: &[u8], optional_padding: bool) -> Result<Vec<u8>, DecodeError> {
|
||||
let (symbols, pad) = if self.padded || optional_padding {
|
||||
if !optional_padding && !text.len().is_multiple_of(4) {
|
||||
return Err(DecodeError);
|
||||
}
|
||||
let pad = text.iter().rev().take(2).take_while(|c| **c == b'=').count();
|
||||
@@ -120,7 +132,8 @@ impl Config {
|
||||
};
|
||||
// A last group of one symbol holds under eight bits; with padding, `=` fills it to four.
|
||||
let rest = symbols.len() % 4;
|
||||
if rest == 1 || (self.padded && pad != (4 - rest) % 4) {
|
||||
let needed = (4 - rest) % 4;
|
||||
if rest == 1 || (optional_padding && pad > needed) || (!optional_padding && self.padded && pad != needed) {
|
||||
return Err(DecodeError);
|
||||
}
|
||||
let mut out = Vec::with_capacity(symbols.len().saturating_mul(3) / 4);
|
||||
|
||||
@@ -79,3 +79,45 @@ proptest! {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Missing padding is opt-in; other canonical validation stays unchanged.
|
||||
#[test]
|
||||
fn optional_padding_keeps_alphabet_placement_and_tail_bit_checks() {
|
||||
for cfg in CONFIGS {
|
||||
for (input, expected) in [("", ""), ("Zg", "f"), ("Zg=", "f"), ("Zg==", "f"), ("Zm8", "fo"), ("Zm8=", "fo"), ("Zm9v", "foo")] {
|
||||
assert_eq!(cfg.decode_optional_padding(input).unwrap(), expected.as_bytes());
|
||||
}
|
||||
for bad in ["=", "====", "Z", "Z===", "Zg===", "Zm8==", "Zm9v=", "QQ==QUJD", "Zm=v", "Zh", "Zh=", "Zh==", "Zm9", "Zm9=", "Zg\n", " Zg", "é"]
|
||||
{
|
||||
assert!(cfg.decode_optional_padding(bad).is_err(), "{cfg:?}: {bad:?}");
|
||||
}
|
||||
}
|
||||
assert_eq!(STANDARD.decode_optional_padding("+/8").unwrap(), [251, 255]);
|
||||
assert_eq!(URL_SAFE.decode_optional_padding("-_8=").unwrap(), [251, 255]);
|
||||
assert!(STANDARD.decode_optional_padding("-_8=").is_err());
|
||||
assert!(URL_SAFE.decode_optional_padding("+/8=").is_err());
|
||||
assert!(STANDARD.decode("Zg=").is_err());
|
||||
assert!(STANDARD_NO_PAD.decode("Zg==").is_err());
|
||||
}
|
||||
|
||||
proptest! {
|
||||
#[test]
|
||||
fn optional_padding_accepts_only_a_suffix_of_required_padding(
|
||||
data in proptest::collection::vec(any::<u8>(), 0..400),
|
||||
junk in proptest::collection::vec(any::<u8>(), 0..128),
|
||||
) {
|
||||
for cfg in [STANDARD, URL_SAFE] {
|
||||
let encoded = cfg.encode(&data);
|
||||
let bare = encoded.trim_end_matches('=');
|
||||
for length in bare.len()..=encoded.len() {
|
||||
prop_assert_eq!(cfg.decode_optional_padding(&encoded[..length]).ok(), Some(data.clone()));
|
||||
}
|
||||
if let Ok(decoded) = cfg.decode_optional_padding(&junk) {
|
||||
let canonical = cfg.encode(decoded);
|
||||
let bare = canonical.trim_end_matches('=');
|
||||
prop_assert!(junk.len() >= bare.len() && junk.len() <= canonical.len());
|
||||
prop_assert_eq!(canonical.as_bytes().get(..junk.len()), Some(junk.as_slice()));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user