1use crate::errors::{
6 BlobIdFromSliceError, BlobIdParseError, CupMissingField, ResolutionContextError,
7};
8use fidl_fuchsia_pkg as fidl;
9use proptest_derive::Arbitrary;
10use serde::{Deserialize, Serialize};
11use std::{fmt, str};
12use typed_builder::TypedBuilder;
13
14pub(crate) const BLOB_ID_SIZE: usize = 32;
15
16#[derive(Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash, Serialize, Deserialize, Arbitrary)]
18pub struct BlobId(#[serde(with = "hex::serde")] [u8; BLOB_ID_SIZE]);
19
20impl BlobId {
21 pub fn parse(s: &str) -> Result<Self, BlobIdParseError> {
32 s.parse()
33 }
34 pub fn as_bytes(&self) -> &[u8] {
36 &self.0[..]
37 }
38}
39
40impl str::FromStr for BlobId {
41 type Err = BlobIdParseError;
42
43 fn from_str(s: &str) -> Result<Self, Self::Err> {
44 let bytes = hex::decode(s)?;
45 if bytes.len() != BLOB_ID_SIZE {
46 return Err(BlobIdParseError::InvalidLength(bytes.len()));
47 }
48 if s.chars().any(|c| c.is_uppercase()) {
49 return Err(BlobIdParseError::CannotContainUppercase);
50 }
51 let mut res: [u8; BLOB_ID_SIZE] = [0; BLOB_ID_SIZE];
52 res.copy_from_slice(&bytes[..]);
53 Ok(Self(res))
54 }
55}
56
57impl From<[u8; BLOB_ID_SIZE]> for BlobId {
58 fn from(bytes: [u8; BLOB_ID_SIZE]) -> Self {
59 Self(bytes)
60 }
61}
62
63impl From<fidl::BlobId> for BlobId {
64 fn from(id: fidl::BlobId) -> Self {
65 Self(id.merkle_root)
66 }
67}
68
69impl From<BlobId> for fidl::BlobId {
70 fn from(id: BlobId) -> Self {
71 Self { merkle_root: id.0 }
72 }
73}
74
75impl From<fuchsia_hash::Hash> for BlobId {
76 fn from(hash: fuchsia_hash::Hash) -> Self {
77 Self(hash.into())
78 }
79}
80
81impl TryFrom<&[u8]> for BlobId {
82 type Error = BlobIdFromSliceError;
83
84 fn try_from(bytes: &[u8]) -> Result<Self, Self::Error> {
85 Ok(Self(bytes.try_into().map_err(|_| Self::Error::InvalidLength(bytes.len()))?))
86 }
87}
88
89impl From<BlobId> for fuchsia_hash::Hash {
90 fn from(id: BlobId) -> Self {
91 id.0.into()
92 }
93}
94
95impl fmt::Display for BlobId {
96 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
97 f.write_str(&hex::encode(self.0))
98 }
99}
100
101impl fmt::Debug for BlobId {
102 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
103 f.write_str(&self.to_string())
104 }
105}
106
107#[derive(Copy, Clone, Debug, Eq, PartialEq, Ord, PartialOrd, Hash, Arbitrary)]
109pub struct BlobInfo {
110 pub blob_id: BlobId,
111 pub length: u64,
112}
113
114impl BlobInfo {
115 pub fn new(blob_id: BlobId, length: u64) -> Self {
116 BlobInfo { blob_id: blob_id, length: length }
117 }
118}
119
120impl From<fidl::BlobInfo> for BlobInfo {
121 fn from(info: fidl::BlobInfo) -> Self {
122 BlobInfo { blob_id: info.blob_id.into(), length: info.length }
123 }
124}
125
126impl From<BlobInfo> for fidl::BlobInfo {
127 fn from(info: BlobInfo) -> Self {
128 Self { blob_id: info.blob_id.into(), length: info.length }
129 }
130}
131
132#[derive(Clone, Debug, Eq, PartialEq, Ord, PartialOrd, Hash)]
134pub struct ResolutionContext {
135 blob_id: Option<BlobId>,
136}
137
138impl ResolutionContext {
139 pub fn new() -> Self {
141 Self { blob_id: None }
142 }
143
144 pub fn blob_id(&self) -> Option<&BlobId> {
146 self.blob_id.as_ref()
147 }
148}
149
150impl From<BlobId> for ResolutionContext {
151 fn from(blob_id: BlobId) -> Self {
152 Self { blob_id: Some(blob_id) }
153 }
154}
155
156impl From<fuchsia_hash::Hash> for ResolutionContext {
157 fn from(hash: fuchsia_hash::Hash) -> Self {
158 Self { blob_id: Some(hash.into()) }
159 }
160}
161
162impl TryFrom<&[u8]> for ResolutionContext {
163 type Error = ResolutionContextError;
164
165 fn try_from(bytes: &[u8]) -> Result<Self, Self::Error> {
166 if bytes.is_empty() {
167 Ok(Self { blob_id: None })
168 } else {
169 Ok(Self { blob_id: Some(bytes.try_into().map_err(Self::Error::InvalidBlobId)?) })
170 }
171 }
172}
173
174impl TryFrom<&fidl::ResolutionContext> for ResolutionContext {
175 type Error = ResolutionContextError;
176
177 fn try_from(context: &fidl::ResolutionContext) -> Result<Self, Self::Error> {
178 Self::try_from(context.bytes.as_slice())
179 }
180}
181
182impl From<ResolutionContext> for Vec<u8> {
183 fn from(context: ResolutionContext) -> Self {
184 match context.blob_id {
185 Some(blob_id) => blob_id.as_bytes().to_vec(),
186 None => vec![],
187 }
188 }
189}
190
191impl From<ResolutionContext> for fidl::ResolutionContext {
192 fn from(context: ResolutionContext) -> Self {
193 Self { bytes: context.into() }
194 }
195}
196
197#[derive(Clone, Debug, Eq, PartialEq, TypedBuilder)]
198pub struct CupData {
199 #[builder(default, setter(into))]
200 pub request: Vec<u8>,
201 #[builder(default, setter(into))]
202 pub key_id: u64,
203 #[builder(default, setter(into))]
204 pub nonce: [u8; 32],
205 #[builder(default, setter(into))]
206 pub response: Vec<u8>,
207 #[builder(default, setter(into))]
208 pub signature: Vec<u8>,
209}
210
211impl From<CupData> for fidl::CupData {
212 fn from(c: CupData) -> Self {
213 fidl::CupData {
214 request: Some(c.request),
215 key_id: Some(c.key_id),
216 nonce: Some(c.nonce),
217 response: Some(c.response),
218 signature: Some(c.signature),
219 ..Default::default()
220 }
221 }
222}
223
224impl TryFrom<fidl::CupData> for CupData {
225 type Error = CupMissingField;
226 fn try_from(c: fidl::CupData) -> Result<Self, Self::Error> {
227 Ok(CupData::builder()
228 .request(c.request.ok_or(CupMissingField::Request)?)
229 .response(c.response.ok_or(CupMissingField::Response)?)
230 .key_id(c.key_id.ok_or(CupMissingField::KeyId)?)
231 .nonce(c.nonce.ok_or(CupMissingField::Nonce)?)
232 .signature(c.signature.ok_or(CupMissingField::Signature)?)
233 .build())
234 }
235}
236
237#[cfg(test)]
238mod test_blob_id {
239 use super::*;
240 use assert_matches::assert_matches;
241 use proptest::prelude::*;
242
243 prop_compose! {
244 fn invalid_hex_char()(c in "[[:ascii:]&&[^0-9a-fA-F]]") -> char {
245 assert_eq!(c.len(), 1);
246 c.chars().next().unwrap()
247 }
248 }
249
250 proptest! {
251 #![proptest_config(ProptestConfig{
252 failure_persistence: None,
255 .. ProptestConfig::default()
256 })]
257
258 #[test]
259 fn parse_is_inverse_of_display(ref id in "[0-9a-f]{64}") {
260 prop_assert_eq!(
261 id,
262 &format!("{}", id.parse::<BlobId>().unwrap())
263 );
264 }
265
266 #[test]
267 fn parse_is_inverse_of_debug(ref id in "[0-9a-f]{64}") {
268 prop_assert_eq!(
269 id,
270 &format!("{:?}", id.parse::<BlobId>().unwrap())
271 );
272 }
273
274 #[test]
275 fn parse_rejects_uppercase(ref id in "[0-9A-F]{64}") {
276 prop_assert_eq!(
277 id.parse::<BlobId>(),
278 Err(BlobIdParseError::CannotContainUppercase)
279 );
280 }
281
282 #[test]
283 fn parse_rejects_unexpected_characters(mut id in "[0-9a-f]{64}", c in invalid_hex_char(), index in 0usize..63) {
284 id.remove(index);
285 id.insert(index, c);
286 prop_assert_eq!(
287 id.parse::<BlobId>(),
288 Err(BlobIdParseError::FromHexError(
289 hex::FromHexError::InvalidHexCharacter { c: c, index: index }
290 ))
291 );
292 }
293
294 #[test]
295 fn parse_expects_even_sized_strings(ref id in "[0-9a-f]([0-9a-f]{2})*") {
296 prop_assert_eq!(
297 id.parse::<BlobId>(),
298 Err(BlobIdParseError::FromHexError(hex::FromHexError::OddLength))
299 );
300 }
301
302 #[test]
303 fn parse_expects_precise_count_of_bytes(ref id in "([0-9a-f]{2})*") {
304 prop_assume!(id.len() != BLOB_ID_SIZE * 2);
305 prop_assert_eq!(
306 id.parse::<BlobId>(),
307 Err(BlobIdParseError::InvalidLength(id.len() / 2))
308 );
309 }
310
311 #[test]
312 fn fidl_conversions_are_inverses(id: BlobId) {
313 let temp : fidl::BlobId = id.into();
314 prop_assert_eq!(
315 id,
316 BlobId::from(temp)
317 );
318 }
319 }
320
321 #[test]
322 fn try_from_slice_rejects_invalid_length() {
323 assert_matches!(
324 BlobId::try_from([0u8; BLOB_ID_SIZE - 1].as_slice()),
325 Err(BlobIdFromSliceError::InvalidLength(31))
326 );
327 assert_matches!(
328 BlobId::try_from([0u8; BLOB_ID_SIZE + 1].as_slice()),
329 Err(BlobIdFromSliceError::InvalidLength(33))
330 );
331 }
332
333 #[test]
334 fn try_from_slice_succeeds() {
335 let bytes = [1u8; 32];
336 assert_eq!(BlobId::try_from(bytes.as_slice()).unwrap().as_bytes(), bytes.as_slice());
337 }
338}
339
340#[cfg(test)]
341mod test_resolution_context {
342 use super::*;
343 use assert_matches::assert_matches;
344
345 #[test]
346 fn try_from_slice_succeeds() {
347 assert_eq!(
348 ResolutionContext::try_from([].as_slice()).unwrap(),
349 ResolutionContext { blob_id: None }
350 );
351
352 assert_eq!(
353 ResolutionContext::try_from([1u8; 32].as_slice()).unwrap(),
354 ResolutionContext { blob_id: Some([1u8; 32].into()) }
355 );
356 }
357
358 #[test]
359 fn try_from_slice_fails() {
360 assert_matches!(
361 ResolutionContext::try_from([1u8].as_slice()),
362 Err(ResolutionContextError::InvalidBlobId(_))
363 );
364 }
365
366 #[test]
367 fn into_vec() {
368 assert_eq!(Vec::from(ResolutionContext::new()), Vec::<u8>::new());
369
370 assert_eq!(Vec::from(ResolutionContext::from(BlobId::from([1u8; 32]))), vec![1u8; 32]);
371 }
372
373 #[test]
374 fn try_from_fidl_succeeds() {
375 assert_eq!(
376 ResolutionContext::try_from(&fidl::ResolutionContext { bytes: vec![] }).unwrap(),
377 ResolutionContext { blob_id: None }
378 );
379
380 assert_eq!(
381 ResolutionContext::try_from(&fidl::ResolutionContext { bytes: vec![1u8; 32] }).unwrap(),
382 ResolutionContext { blob_id: Some([1u8; 32].into()) }
383 );
384 }
385
386 #[test]
387 fn try_from_fidl_fails() {
388 assert_matches!(
389 ResolutionContext::try_from(&fidl::ResolutionContext { bytes: vec![1u8; 1] }),
390 Err(ResolutionContextError::InvalidBlobId(_))
391 );
392 }
393
394 #[test]
395 fn into_fidl() {
396 assert_eq!(
397 fidl::ResolutionContext::from(ResolutionContext::new()),
398 fidl::ResolutionContext { bytes: vec![] }
399 );
400
401 assert_eq!(
402 fidl::ResolutionContext::from(ResolutionContext::from(BlobId::from([1u8; 32]))),
403 fidl::ResolutionContext { bytes: vec![1u8; 32] }
404 );
405 }
406}