Skip to content

Commit

Permalink
Merge pull request #471 from ytanay/fix-base64-deserialization-borrowed
Browse files Browse the repository at this point in the history
Fix base64 deserialization when using a reader
  • Loading branch information
Byron authored Feb 3, 2024
2 parents 00a3e18 + a8d7356 commit b74056b
Showing 1 changed file with 21 additions and 5 deletions.
26 changes: 21 additions & 5 deletions google-apis-common/src/serde.rs
Original file line number Diff line number Diff line change
Expand Up @@ -139,7 +139,8 @@ pub mod duration {
pub mod standard_base64 {
use serde::{Deserialize, Deserializer, Serializer};
use serde_with::{DeserializeAs, SerializeAs};

use std::borrow::Cow;

pub struct Wrapper;

pub fn to_string(bytes: &Vec<u8>) -> String {
Expand All @@ -160,15 +161,16 @@ pub mod standard_base64 {
where
D: Deserializer<'de>,
{
let s: &str = Deserialize::deserialize(deserializer)?;
base64::decode_config(s, base64::STANDARD).map_err(serde::de::Error::custom)
let s: Cow<str> = Deserialize::deserialize(deserializer)?;
base64::decode_config(s.as_ref(), base64::STANDARD).map_err(serde::de::Error::custom)
}
}
}

pub mod urlsafe_base64 {
use serde::{Deserialize, Deserializer, Serializer};
use serde_with::{DeserializeAs, SerializeAs};
use std::borrow::Cow;

pub struct Wrapper;

Expand All @@ -190,8 +192,8 @@ pub mod urlsafe_base64 {
where
D: Deserializer<'de>,
{
let s: &str = Deserialize::deserialize(deserializer)?;
base64::decode_config(s, base64::URL_SAFE).map_err(serde::de::Error::custom)
let s: Cow<str> = Deserialize::deserialize(deserializer)?;
base64::decode_config(s.as_ref(), base64::URL_SAFE).map_err(serde::de::Error::custom)
}
}
}
Expand Down Expand Up @@ -301,13 +303,27 @@ mod test {
assert_eq!(Some(b"qXZo9:Smn:C~3)EXTI1QKtHv1(fTz}".as_slice()), wrapper.bytes.as_deref());
}

#[test]
fn standard_base64_de_reader_success_cases() {
let standard: Base64StandardWrapper =
serde_json::from_reader(r#"{"bytes": "cVhabzk6U21uOkN+MylFWFRJMVFLdEh2MShmVHp9"}"#.as_bytes()).unwrap();
assert_eq!(Some(b"qXZo9:Smn:C~3)EXTI1QKtHv1(fTz}".as_slice()), standard.bytes.as_deref());
}

#[test]
fn urlsafe_base64_de_success_cases() {
let wrapper: Base64URLSafeWrapper =
serde_json::from_str(r#"{"bytes": "aGVsbG8gd29ybGQ="}"#).unwrap();
assert_eq!(Some(b"hello world".as_slice()), wrapper.bytes.as_deref());
}

#[test]
fn urlsafe_base64_de_reader_success_cases() {
let wrapper: Base64URLSafeWrapper =
serde_json::from_reader(r#"{"bytes": "aGVsbG8gd29ybGQ="}"#.as_bytes()).unwrap();
assert_eq!(Some(b"hello world".as_slice()), wrapper.bytes.as_deref());
}

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

0 comments on commit b74056b

Please sign in to comment.