Skip to content

Commit

Permalink
Merge pull request #506 from dantreiman/tolerant_base64_decoders
Browse files Browse the repository at this point in the history
Tolerant base64 decoding.  Accept url-safe or standard encoding in responses.
  • Loading branch information
Byron authored Jun 12, 2024
2 parents 46107ff + b5bc9d6 commit 7b70b66
Showing 1 changed file with 29 additions and 3 deletions.
32 changes: 29 additions & 3 deletions google-apis-common/src/serde.rs
Original file line number Diff line number Diff line change
Expand Up @@ -170,7 +170,13 @@ pub mod standard_base64 {
D: Deserializer<'de>,
{
let s: Cow<str> = Deserialize::deserialize(deserializer)?;
base64::prelude::BASE64_STANDARD.decode(s.as_ref()).map_err(serde::de::Error::custom)
match base64::prelude::BASE64_STANDARD.decode(s.as_ref()) {
Ok(decoded) => Ok(decoded),
Err(first_err) => match base64::prelude::BASE64_URL_SAFE.decode(s.as_ref()) {
Ok(decoded) => Ok(decoded),
Err(_) => Err(serde::de::Error::custom(first_err))
}
}
}
}
}
Expand Down Expand Up @@ -202,7 +208,13 @@ pub mod urlsafe_base64 {
D: Deserializer<'de>,
{
let s: Cow<str> = Deserialize::deserialize(deserializer)?;
base64::prelude::BASE64_URL_SAFE.decode(s.as_ref()).map_err(serde::de::Error::custom)
match base64::prelude::BASE64_URL_SAFE.decode(s.as_ref()) {
Ok(decoded) => Ok(decoded),
Err(first_err) => match base64::prelude::BASE64_STANDARD.decode(s.as_ref()) {
Ok(decoded) => Ok(decoded),
Err(_) => Err(serde::de::Error::custom(first_err))
}
}
}
}
}
Expand Down Expand Up @@ -343,14 +355,28 @@ mod test {
assert_eq!(Some(b"hello world".as_slice()), wrapper.bytes.as_deref());
}

#[test]
fn urlsafe_base64_de_standard_success_cases() {
let wrapper: Base64URLSafeWrapper = // Expect URL-safe base64 accepts standard encoding
serde_json::from_reader(r#"{"bytes": "REE/P0V+Nz4oIWtH"}"#.as_bytes()).unwrap();
assert_eq!(Some(b"DA??E~7>(!kG".as_slice()), wrapper.bytes.as_deref());
}

#[test]
fn urlsafe_base64_de_failure_cases() {
assert!(
serde_json::from_str::<Base64URLSafeWrapper>(r#"{"bytes": "aGVsbG8gd29ybG+Q"}"#)
serde_json::from_str::<Base64URLSafeWrapper>(r#"{"bytes": "aGVsbG8gd29ybG&Q"}"#)
.is_err()
);
}

#[test]
fn standard_base64_de_urlsafe_success_cases() {
let wrapper: Base64URLSafeWrapper = // Expect standard base64 accepts url-safe encoding
serde_json::from_reader(r#"{"bytes": "REE_P0V-Nz4oIWtH"}"#.as_bytes()).unwrap();
assert_eq!(Some(b"DA??E~7>(!kG".as_slice()), wrapper.bytes.as_deref());
}

#[test]
fn standard_base64_de_failure_cases() {
assert!(serde_json::from_str::<Base64StandardWrapper>(r#"{"bytes": "%"}"#).is_err());
Expand Down

0 comments on commit 7b70b66

Please sign in to comment.