Skip to main content

countersign_protocol/wire/
values.rs

1use std::fmt;
2
3use base64::Engine;
4use base64::engine::general_purpose::{STANDARD, URL_SAFE_NO_PAD};
5use serde::de::{Error as _, SeqAccess, Visitor};
6use serde::{Deserialize, Deserializer, Serialize, Serializer};
7use thiserror::Error;
8
9#[derive(Debug, Error)]
10#[error("invalid or oversized wire value")]
11pub struct InvalidValue;
12
13#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
14#[serde(try_from = "String", into = "String")]
15pub struct Id(String);
16
17impl Id {
18    pub fn new(value: impl Into<String>) -> Result<Self, InvalidValue> {
19        value.into().try_into()
20    }
21    pub fn as_str(&self) -> &str {
22        &self.0
23    }
24}
25
26impl TryFrom<String> for Id {
27    type Error = InvalidValue;
28    fn try_from(value: String) -> Result<Self, Self::Error> {
29        if value.is_empty() || value.len() > 256 || value.chars().any(char::is_control) {
30            return Err(InvalidValue);
31        }
32        Ok(Self(value))
33    }
34}
35
36impl From<Id> for String {
37    fn from(value: Id) -> Self {
38        value.0
39    }
40}
41
42#[derive(Clone, PartialEq, Eq)]
43pub struct FixedBytes<const N: usize>(pub [u8; N]);
44pub type Fingerprint = FixedBytes<32>;
45
46impl<const N: usize> FixedBytes<N> {
47    pub fn new(bytes: [u8; N]) -> Self {
48        Self(bytes)
49    }
50    pub fn as_slice(&self) -> &[u8] {
51        &self.0
52    }
53}
54
55impl<const N: usize> fmt::Debug for FixedBytes<N> {
56    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
57        write!(f, "FixedBytes<{N}>")
58    }
59}
60impl<const N: usize> Serialize for FixedBytes<N> {
61    fn serialize<S: Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
62        s.serialize_str(&STANDARD.encode(self.0))
63    }
64}
65impl<'de, const N: usize> Deserialize<'de> for FixedBytes<N> {
66    fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
67        let text = String::deserialize(d)?;
68        if text.len() != N.div_ceil(3) * 4 {
69            return Err(D::Error::custom(InvalidValue));
70        }
71        let bytes = STANDARD.decode(text).map_err(D::Error::custom)?;
72        Ok(Self(
73            bytes
74                .try_into()
75                .map_err(|_| D::Error::custom(InvalidValue))?,
76        ))
77    }
78}
79
80pub const MAX_SIGNING_INPUT: usize = 256 * 1024;
81pub const MAX_CHAIN_BYTES: usize = 256 * 1024;
82pub const MAX_CERTIFICATES: usize = 16;
83pub type SigningInput = Bytes<MAX_SIGNING_INPUT>;
84pub type SignatureBytes = Bytes<2048>;
85
86#[derive(Clone, PartialEq, Eq)]
87pub struct Bytes<const MAX: usize>(Vec<u8>);
88
89impl<const MAX: usize> Bytes<MAX> {
90    pub fn new(value: Vec<u8>) -> Result<Self, InvalidValue> {
91        if value.is_empty() || value.len() > MAX {
92            return Err(InvalidValue);
93        }
94        Ok(Self(value))
95    }
96    pub fn as_slice(&self) -> &[u8] {
97        &self.0
98    }
99}
100
101impl<const MAX: usize> fmt::Debug for Bytes<MAX> {
102    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
103        write!(f, "Bytes(len={})", self.0.len())
104    }
105}
106impl<const MAX: usize> Serialize for Bytes<MAX> {
107    fn serialize<S: Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
108        s.serialize_str(&STANDARD.encode(&self.0))
109    }
110}
111impl<'de, const MAX: usize> Deserialize<'de> for Bytes<MAX> {
112    fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
113        let text = String::deserialize(d)?;
114        if text.len() > MAX.div_ceil(3) * 4 {
115            return Err(D::Error::custom(InvalidValue));
116        }
117        let bytes = STANDARD.decode(text).map_err(D::Error::custom)?;
118        Self::new(bytes).map_err(D::Error::custom)
119    }
120}
121
122#[derive(Clone, PartialEq, Eq, Debug, Serialize)]
123pub struct PublicChain(Vec<Bytes<MAX_CHAIN_BYTES>>);
124impl PublicChain {
125    pub fn new(ders: Vec<Vec<u8>>) -> Result<Self, InvalidValue> {
126        if ders.is_empty() || ders.len() > MAX_CERTIFICATES {
127            return Err(InvalidValue);
128        }
129        let mut total = 0usize;
130        let mut certs = Vec::with_capacity(ders.len());
131        for der in ders {
132            let cert = Bytes::new(der)?;
133            total += cert.0.len();
134            if total > MAX_CHAIN_BYTES {
135                return Err(InvalidValue);
136            }
137            certs.push(cert);
138        }
139        Ok(Self(certs))
140    }
141    pub fn as_slice(&self) -> &[Bytes<MAX_CHAIN_BYTES>] {
142        &self.0
143    }
144}
145impl<'de> Deserialize<'de> for PublicChain {
146    fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
147        struct ChainVisitor;
148        impl<'de> Visitor<'de> for ChainVisitor {
149            type Value = PublicChain;
150            fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
151                f.write_str("a bounded nonempty public DER chain")
152            }
153            fn visit_seq<A: SeqAccess<'de>>(self, mut seq: A) -> Result<Self::Value, A::Error> {
154                let mut certs = Vec::new();
155                let mut total = 0;
156                while let Some(cert) = seq.next_element::<Bytes<MAX_CHAIN_BYTES>>()? {
157                    total += cert.0.len();
158                    if certs.len() == MAX_CERTIFICATES || total > MAX_CHAIN_BYTES {
159                        return Err(A::Error::custom(InvalidValue));
160                    }
161                    certs.push(cert);
162                }
163                if certs.is_empty() {
164                    return Err(A::Error::custom(InvalidValue));
165                }
166                Ok(PublicChain(certs))
167            }
168        }
169        d.deserialize_seq(ChainVisitor)
170    }
171}
172
173#[derive(Clone, Serialize, Deserialize)]
174#[serde(try_from = "String", into = "String")]
175pub struct CompactJws(String);
176impl CompactJws {
177    pub fn as_str(&self) -> &str {
178        &self.0
179    }
180}
181impl fmt::Debug for CompactJws {
182    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
183        f.write_str("CompactJws([redacted])")
184    }
185}
186impl TryFrom<String> for CompactJws {
187    type Error = InvalidValue;
188    fn try_from(s: String) -> Result<Self, Self::Error> {
189        if s.len() > 16384 {
190            return Err(InvalidValue);
191        }
192        let mut parts = s.split('.');
193        for i in 0..3 {
194            let bytes = URL_SAFE_NO_PAD
195                .decode(parts.next().ok_or(InvalidValue)?)
196                .map_err(|_| InvalidValue)?;
197            if bytes.is_empty() || (i == 2 && bytes.len() != 64) {
198                return Err(InvalidValue);
199            }
200        }
201        if parts.next().is_some() {
202            return Err(InvalidValue);
203        }
204        Ok(Self(s))
205    }
206}
207impl From<CompactJws> for String {
208    fn from(value: CompactJws) -> Self {
209        value.0
210    }
211}