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
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
use std::ops::{Deref, DerefMut};

use serde::{de::Visitor, Deserialize, Deserializer, Serialize};
use typeshare::typeshare;

use super::encoding;

/// A newtype around `Vec<u8>` which serializes using the transport format's byte representation.
///
/// When feature `serialize_bytes_as_base64_string` is set, this type will be serialized into a
/// `base64url` representation instead. Note that this type should not be used externally when this
/// feature is set, such as in Kotlin, to avoid a serialization errors. In the future, this feature
/// flag can be removed when typeshare supports target/language specific serialization:
/// <https://github.com/1Password/typeshare/issues/63>
///
/// This will use an array of numbers for JSON, and a byte string in CBOR for example.
///
/// It also supports deserializing from `base64` and `base64url` formatted strings.
#[typeshare(transparent)]
#[derive(Debug, Default, PartialEq, Eq, Clone)]
#[repr(transparent)]
pub struct Bytes(Vec<u8>);

impl Deref for Bytes {
    type Target = Vec<u8>;

    fn deref(&self) -> &Self::Target {
        &self.0
    }
}

impl DerefMut for Bytes {
    fn deref_mut(&mut self) -> &mut Self::Target {
        &mut self.0
    }
}

impl From<Vec<u8>> for Bytes {
    fn from(inner: Vec<u8>) -> Self {
        Bytes(inner)
    }
}

impl From<Bytes> for Vec<u8> {
    fn from(src: Bytes) -> Self {
        src.0
    }
}

impl From<Bytes> for String {
    fn from(src: Bytes) -> Self {
        encoding::base64url(&src)
    }
}

/// The string given for decoding is not `base64url` nor `base64` encoded data.
#[derive(Debug)]
pub struct NotBase64Encoded;

impl TryFrom<&str> for Bytes {
    type Error = NotBase64Encoded;

    fn try_from(value: &str) -> Result<Self, Self::Error> {
        encoding::try_from_base64url(value)
            .or_else(|| encoding::try_from_base64(value))
            .ok_or(NotBase64Encoded)
            .map(Self)
    }
}

impl FromIterator<u8> for Bytes {
    fn from_iter<T: IntoIterator<Item = u8>>(iter: T) -> Self {
        Bytes(iter.into_iter().collect())
    }
}

impl IntoIterator for Bytes {
    type Item = u8;

    type IntoIter = std::vec::IntoIter<u8>;

    fn into_iter(self) -> Self::IntoIter {
        self.0.into_iter()
    }
}

impl<'a> IntoIterator for &'a Bytes {
    type Item = &'a u8;

    type IntoIter = std::slice::Iter<'a, u8>;

    fn into_iter(self) -> Self::IntoIter {
        self.0.iter()
    }
}

impl Serialize for Bytes {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: serde::Serializer,
    {
        if cfg!(feature = "serialize_bytes_as_base64_string") {
            serializer.serialize_str(&crate::encoding::base64url(&self.0))
        } else {
            serializer.serialize_bytes(&self.0)
        }
    }
}

impl<'de> Deserialize<'de> for Bytes {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        struct Base64Visitor;

        impl<'de> Visitor<'de> for Base64Visitor {
            type Value = Bytes;

            fn expecting(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
                write!(f, "A vector of bytes or a base46(url) encoded string")
            }
            fn visit_borrowed_str<E>(self, v: &'de str) -> Result<Self::Value, E>
            where
                E: serde::de::Error,
            {
                self.visit_str(v)
            }
            fn visit_string<E>(self, v: String) -> Result<Self::Value, E>
            where
                E: serde::de::Error,
            {
                self.visit_str(&v)
            }
            fn visit_str<E>(self, v: &str) -> Result<Self::Value, E>
            where
                E: serde::de::Error,
            {
                v.try_into().map_err(|_| {
                    E::invalid_value(
                        serde::de::Unexpected::Str(v),
                        &"A base64(url) encoded string",
                    )
                })
            }
            fn visit_seq<A>(self, mut seq: A) -> Result<Self::Value, A::Error>
            where
                A: serde::de::SeqAccess<'de>,
            {
                let mut buf = Vec::with_capacity(seq.size_hint().unwrap_or_default());
                while let Some(byte) = seq.next_element()? {
                    buf.push(byte);
                }
                Ok(Bytes(buf))
            }
        }
        deserializer.deserialize_any(Base64Visitor)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::collections::HashMap;
    #[test]
    fn deserialize_many_formats_into_base64urlvec() {
        let json = r#"{
            "array": [101,195,212,161,191,112,75,189,152,52,121,17,62,113,114,164],
            "base64url": "ZcPUob9wS72YNHkRPnFypA",
            "base64": "ZcPUob9wS72YNHkRPnFypA=="
        }"#;

        let deserialized: HashMap<&str, Bytes> =
            serde_json::from_str(json).expect("failed to deserialize");

        assert_eq!(deserialized["array"], deserialized["base64url"]);
        assert_eq!(deserialized["base64url"], deserialized["base64"]);
    }

    #[test]
    fn deserialization_should_fail() {
        let json = r#"{
            "array": ["ZcPUob9wS72YNHkRPnFypA","ZcPUob9wS72YNHkRPnFypA=="],
        }"#;

        serde_json::from_str::<HashMap<&str, Bytes>>(json)
            .expect_err("did not give an error as expected.");
    }
}