1use std::fmt;
20
21pub const FORMAT: u8 = 1;
23
24pub const MAX_KEY_REF: usize = 1024;
26
27pub const MAX_CIPHERTEXT: usize = 8192;
29
30#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
34#[non_exhaustive]
35pub enum BackendKind {
36 AwsKms,
38 GcpKms,
40 AzureKeyVault,
42 VaultTransit,
44 OpenbaoTransit,
46 Pkcs11,
48}
49
50impl BackendKind {
51 pub const ALL: [BackendKind; 6] = [
53 BackendKind::AwsKms,
54 BackendKind::GcpKms,
55 BackendKind::AzureKeyVault,
56 BackendKind::VaultTransit,
57 BackendKind::OpenbaoTransit,
58 BackendKind::Pkcs11,
59 ];
60
61 #[must_use]
64 pub fn name(self) -> &'static str {
65 match self {
66 BackendKind::AwsKms => "aws-kms",
67 BackendKind::GcpKms => "gcp-kms",
68 BackendKind::AzureKeyVault => "azure-key-vault",
69 BackendKind::VaultTransit => "vault-transit",
70 BackendKind::OpenbaoTransit => "openbao-transit",
71 BackendKind::Pkcs11 => "pkcs11",
72 }
73 }
74
75 #[must_use]
77 pub fn from_name(name: &str) -> Option<BackendKind> {
78 BackendKind::ALL.into_iter().find(|k| k.name() == name)
79 }
80
81 fn byte(self) -> u8 {
83 match self {
84 BackendKind::AwsKms => 1,
85 BackendKind::GcpKms => 2,
86 BackendKind::AzureKeyVault => 3,
87 BackendKind::VaultTransit => 4,
88 BackendKind::OpenbaoTransit => 5,
89 BackendKind::Pkcs11 => 6,
90 }
91 }
92
93 fn from_byte(byte: u8) -> Option<BackendKind> {
95 BackendKind::ALL.into_iter().find(|k| k.byte() == byte)
96 }
97}
98
99impl fmt::Display for BackendKind {
100 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
101 f.write_str(self.name())
102 }
103}
104
105#[derive(Debug, Clone, PartialEq, Eq)]
107#[non_exhaustive]
108pub enum BlobError {
109 Empty,
111 UnknownFormat(u8),
113 UnknownKind(u8),
115 Truncated,
117 TrailingBytes,
119 KeyRef,
121 Ciphertext,
123 RefText,
126}
127
128impl fmt::Display for BlobError {
129 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
130 match self {
131 BlobError::Empty => f.write_str("a key-wrap blob is empty"),
132 BlobError::UnknownFormat(n) => {
133 write!(f, "key-wrap format {n} is not one this build knows")
134 }
135 BlobError::UnknownKind(n) => write!(
136 f,
137 "a key-wrap blob names key backend {n}, which this build does not know"
138 ),
139 BlobError::Truncated => f.write_str("a key-wrap blob is cut short"),
140 BlobError::TrailingBytes => f.write_str("a key-wrap blob has bytes after its end"),
141 BlobError::KeyRef => write!(
142 f,
143 "a key reference is empty, longer than {MAX_KEY_REF} bytes, or not printable ASCII"
144 ),
145 BlobError::Ciphertext => write!(
146 f,
147 "a wrapped key's ciphertext is empty or longer than {MAX_CIPHERTEXT} bytes"
148 ),
149 BlobError::RefText => {
150 f.write_str("a key reference does not start with a key backend's name and a colon")
151 }
152 }
153 }
154}
155
156impl std::error::Error for BlobError {}
157
158#[derive(Debug, Clone, PartialEq, Eq, Hash)]
162pub struct WrapRef {
163 kind: BackendKind,
164 key: String,
165}
166
167impl WrapRef {
168 pub fn new(kind: BackendKind, key: impl Into<String>) -> Result<WrapRef, BlobError> {
176 let key = key.into();
177 if !valid_key(key.as_bytes()) {
178 return Err(BlobError::KeyRef);
179 }
180 Ok(WrapRef { kind, key })
181 }
182
183 pub fn parse(text: &str) -> Result<WrapRef, BlobError> {
192 let (name, key) = text.split_once(':').ok_or(BlobError::RefText)?;
193 let kind = BackendKind::from_name(name).ok_or(BlobError::RefText)?;
194 WrapRef::new(kind, key)
195 }
196
197 #[must_use]
199 pub fn kind(&self) -> BackendKind {
200 self.kind
201 }
202
203 #[must_use]
205 pub fn key(&self) -> &str {
206 &self.key
207 }
208}
209
210impl fmt::Display for WrapRef {
211 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
212 write!(f, "{}:{}", self.kind, self.key)
213 }
214}
215
216#[derive(Clone, PartialEq, Eq)]
219pub struct Blob {
220 reference: WrapRef,
221 ciphertext: Vec<u8>,
222}
223
224impl Blob {
225 pub fn new(reference: WrapRef, ciphertext: Vec<u8>) -> Result<Blob, BlobError> {
232 if !(1..=MAX_CIPHERTEXT).contains(&ciphertext.len()) {
233 return Err(BlobError::Ciphertext);
234 }
235 Ok(Blob {
236 reference,
237 ciphertext,
238 })
239 }
240
241 #[must_use]
243 pub fn encode(&self) -> Vec<u8> {
244 let key = self.reference.key.as_bytes();
245 let key_len = u16::try_from(key.len()).unwrap_or(u16::MAX);
248 let ct_len = u32::try_from(self.ciphertext.len()).unwrap_or(u32::MAX);
249 let mut out = Vec::with_capacity(8 + key.len() + self.ciphertext.len());
250 out.push(FORMAT);
251 out.push(self.reference.kind.byte());
252 out.extend_from_slice(&key_len.to_be_bytes());
253 out.extend_from_slice(key);
254 out.extend_from_slice(&ct_len.to_be_bytes());
255 out.extend_from_slice(&self.ciphertext);
256 out
257 }
258
259 pub fn decode(bytes: &[u8]) -> Result<Blob, BlobError> {
265 let (&format, rest) = bytes.split_first().ok_or(BlobError::Empty)?;
266 if format != FORMAT {
267 return Err(BlobError::UnknownFormat(format));
268 }
269 let (&kind, rest) = rest.split_first().ok_or(BlobError::Truncated)?;
270 let kind = BackendKind::from_byte(kind).ok_or(BlobError::UnknownKind(kind))?;
271 let (key_len, rest) = take::<2>(rest)?;
272 let key_len = usize::from(u16::from_be_bytes(key_len));
273 if !(1..=MAX_KEY_REF).contains(&key_len) {
274 return Err(BlobError::KeyRef);
275 }
276 let (key, rest) = rest.split_at_checked(key_len).ok_or(BlobError::Truncated)?;
277 if !valid_key(key) {
278 return Err(BlobError::KeyRef);
279 }
280 let (ct_len, rest) = take::<4>(rest)?;
281 let ct_len = usize::try_from(u32::from_be_bytes(ct_len)).unwrap_or(usize::MAX);
282 if !(1..=MAX_CIPHERTEXT).contains(&ct_len) {
283 return Err(BlobError::Ciphertext);
284 }
285 let (ciphertext, rest) = rest.split_at_checked(ct_len).ok_or(BlobError::Truncated)?;
286 if !rest.is_empty() {
287 return Err(BlobError::TrailingBytes);
288 }
289 let key = String::from_utf8(key.to_vec()).map_err(|_| BlobError::KeyRef)?;
291 Ok(Blob {
292 reference: WrapRef { kind, key },
293 ciphertext: ciphertext.to_vec(),
294 })
295 }
296
297 #[must_use]
299 pub fn reference(&self) -> &WrapRef {
300 &self.reference
301 }
302
303 #[must_use]
305 pub fn ciphertext(&self) -> &[u8] {
306 &self.ciphertext
307 }
308}
309
310impl fmt::Debug for Blob {
311 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
312 f.debug_struct("Blob")
313 .field("reference", &self.reference)
314 .field("ciphertext_len", &self.ciphertext.len())
315 .finish()
316 }
317}
318
319fn valid_key(key: &[u8]) -> bool {
323 (1..=MAX_KEY_REF).contains(&key.len()) && key.iter().all(u8::is_ascii_graphic)
324}
325
326fn take<const N: usize>(bytes: &[u8]) -> Result<([u8; N], &[u8]), BlobError> {
328 let (head, rest) = bytes.split_at_checked(N).ok_or(BlobError::Truncated)?;
329 let head = head.try_into().map_err(|_| BlobError::Truncated)?;
330 Ok((head, rest))
331}
332
333#[cfg(test)]
334mod tests;