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
//! Base64 data that encodes to url safe base64, but can decode from multiple
//! base64 implementations to account for various clients and libraries. Compatible
//! with serde and JsonSchema.

use std::{convert::TryFrom, fmt};

use serde::{
    de::{Error, Unexpected, Visitor},
    Deserialize, Deserializer, Serialize, Serializer,
};

static ALLOWED_DECODING_FORMATS: &[data_encoding::Encoding] = &[
    data_encoding::BASE64,
    data_encoding::BASE64URL,
    data_encoding::BASE64URL_NOPAD,
    data_encoding::BASE64_MIME,
    data_encoding::BASE64_NOPAD,
];

#[derive(Debug, Clone, PartialEq, Eq)]
/// A container for binary that should be base64 encoded in serialisation. In reverse
/// when deserializing, will decode from many different types of base64 possible.
pub struct Base64Data(pub Vec<u8>);

impl Base64Data {
    /// Return is the data is empty.
    pub fn is_empty(&self) -> bool {
        self.0.is_empty()
    }
}

impl fmt::Display for Base64Data {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}", data_encoding::BASE64URL_NOPAD.encode(&self.0))
    }
}

impl From<Base64Data> for Vec<u8> {
    fn from(data: Base64Data) -> Vec<u8> {
        data.0
    }
}

impl From<Vec<u8>> for Base64Data {
    fn from(data: Vec<u8>) -> Base64Data {
        Base64Data(data)
    }
}

impl AsRef<[u8]> for Base64Data {
    fn as_ref(&self) -> &[u8] {
        &self.0
    }
}

/// Error returned when invalid Base64 data was sent.
#[derive(Default, Debug)]
pub struct CouldNotDecodeBase64Data;

impl std::fmt::Display for CouldNotDecodeBase64Data {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "Could not decode base64 data")
    }
}

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

impl TryFrom<&str> for Base64Data {
    type Error = CouldNotDecodeBase64Data;

    fn try_from(v: &str) -> Result<Self, Self::Error> {
        for config in ALLOWED_DECODING_FORMATS {
            if let Ok(data) = config.decode(v.as_bytes()) {
                return Ok(Base64Data(data));
            }
        }

        Err(CouldNotDecodeBase64Data)
    }
}

struct Base64DataVisitor;

impl<'de> Visitor<'de> for Base64DataVisitor {
    type Value = Base64Data;

    fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
        write!(formatter, "a base64 encoded string")
    }

    fn visit_str<E>(self, v: &str) -> Result<Self::Value, E>
    where
        E: Error,
    {
        // Forgive alt base64 decoding formats
        for config in ALLOWED_DECODING_FORMATS {
            if let Ok(data) = config.decode(v.as_bytes()) {
                return Ok(Base64Data(data));
            }
        }

        Err(serde::de::Error::invalid_value(Unexpected::Str(v), &self))
    }
}

impl<'de> Deserialize<'de> for Base64Data {
    fn deserialize<D>(deserializer: D) -> Result<Self, <D as Deserializer<'de>>::Error>
    where
        D: Deserializer<'de>,
    {
        deserializer.deserialize_str(Base64DataVisitor)
    }
}

impl Serialize for Base64Data {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        let encoded = data_encoding::BASE64URL_NOPAD.encode(&self.0);
        serializer.serialize_str(&encoded)
    }
}

impl schemars::JsonSchema for Base64Data {
    fn schema_name() -> String {
        "Base64Data".to_string()
    }

    fn json_schema(gen: &mut schemars::gen::SchemaGenerator) -> schemars::schema::Schema {
        let mut obj = gen.root_schema_for::<String>().schema;
        // From: https://swagger.io/specification/#data-types
        obj.format = Some("byte".to_string());
        schemars::schema::Schema::Object(obj)
    }

    fn is_referenceable() -> bool {
        false
    }
}

#[cfg(test)]
mod tests {
    use std::convert::TryFrom;

    use crate::base64::Base64Data;

    #[test]
    fn test_base64_try_from() {
        assert!(Base64Data::try_from("aGVsbG8=").is_ok());
        assert!(Base64Data::try_from("abcdefghij").is_err());
    }
}