image4 0.8.2

A no_std-friendly library for parsing and generation of Image4 images written in pure Rust.
Documentation
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
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
use super::{common, ArrayRef, ConstraintRef, DictRef, PropertyOwned, ValueRef};
use crate::Tag;
use alloc::{collections::BTreeMap, vec::Vec};
use der::{
    referenced::OwnedToRef, Decode, Encode, EncodeValue, Header, Length, Reader, SliceWriter,
    Tagged, Writer,
};

macro_rules! def_owned_value {
    (
        $(#[$m:meta])*
        $name:ident,
        $borrowed:ident
        $(,{data: #[$data_meta:meta]})?
        $(,
            $(#[$var_meta:meta])*
            $var:ident($var_tag_num:ident)
        )*
    ) => {
        #[derive(Clone, Eq, PartialEq, Hash, Debug)]
        $(#[$m])*
        pub enum $name {
            /// A boolean value.
            Boolean(bool),
            /// An integer value.
            Integer(u64),
            /// A data value.
            $(#[$data_meta])?
            Data(Vec<u8>),
            /// A dictionary of values.
            Dict(BTreeMap<Tag, $name>),
            /// An array of values.
            Array(Vec<$name>),
            $($(#[$var_meta])* $var,)*
        }

        impl From<bool> for $name {
            fn from(value: bool) -> Self {
                $name::Boolean(value)
            }
        }

        impl From<u8> for $name {
            fn from(value: u8) -> Self {
                $name::Integer(value as u64)
            }
        }

        impl From<u16> for $name {
            fn from(value: u16) -> Self {
                $name::Integer(value as u64)
            }
        }

        impl From<u32> for $name {
            fn from(value: u32) -> Self {
                $name::Integer(value as u64)
            }
        }

        impl From<u64> for $name {
            fn from(value: u64) -> Self {
                $name::Integer(value)
            }
        }

        impl<'a> From<&'a [u8]> for $name {
            fn from(value: &'a [u8]) -> Self {
                $name::Data(value.to_vec())
            }
        }

        impl From<Vec<u8>> for $name {
            fn from(value: Vec<u8>) -> Self {
                $name::Data(value)
            }
        }

        impl<const N: usize> From<[u8; N]> for $name {
            fn from(value: [u8; N]) -> Self {
                $name::Data(value.to_vec())
            }
        }

        impl<'a, const N: usize> From<&'a [u8; N]> for $name {
            fn from(value: &'a [u8; N]) -> Self {
                $name::Data(value.to_vec())
            }
        }

        impl<'a> Decode<'a> for $name {
            fn decode<R: Reader<'a>>(decoder: &mut R) -> der::Result<Self> {
                let position = decoder.position();

                $borrowed::decode(decoder).and_then(|value| {
                    let result = match value {
                        $borrowed::Boolean(v) => Ok(Self::Boolean(v)),
                        $borrowed::Integer(v) => Ok(Self::Integer(v)),
                        $borrowed::Data(v) => Ok(Self::Data(v.to_vec())),
                        $borrowed::Dict(v) => v.decode_owned().map(Self::Dict),
                        $borrowed::Array(v) => v.decode_owned().map(Self::Array),
                        $($borrowed::$var => Ok(Self::$var),)*
                    };

                    result.map_err(|e| $crate::util::shift_error_position(e, position))
                })
            }
        }

        impl Tagged for $name {
            fn tag(&self) -> der::Tag {
                match self {
                    $name::Boolean(_) => ::der::Tag::Boolean,
                    $name::Integer(_) => ::der::Tag::Integer,
                    $name::Data(_) => ::der::Tag::OctetString,
                    $name::Dict(_) => ::der::Tag::Set,
                    $name::Array(_) => ::der::Tag::Sequence,
                    $($name::$var => ::der::Tag::ContextSpecific {
                        constructed: true,
                        number: ::der::TagNumber::$var_tag_num,
                    },)*
                }
            }
        }

        impl ::der::EncodeValue for $name {
            fn value_len(&self) -> ::der::Result<Length> {
                match self {
                    $name::Boolean(value) => value.value_len(),
                    $name::Integer(value) => value.value_len(),
                    $name::Data(data) => ::der::asn1::OctetStringRef::new(data)?.value_len(),
                    $name::Dict(dict) => common::encoded_dict_body_len(dict),
                    $name::Array(array) => array.value_len(),
                    $($name::$var => ::der::asn1::ContextSpecificRef {
                        tag_number: ::der::TagNumber::$var_tag_num,
                        tag_mode: ::der::TagMode::Explicit,
                        value: &(),
                    }.value_len(),)*
                }
            }

            fn encode_value(&self, encoder: &mut impl ::der::Writer) -> ::der::Result<()> {
                match self {
                    $name::Boolean(value) => value.encode_value(encoder),
                    $name::Integer(value) => value.encode_value(encoder),
                    $name::Data(data) => ::der::asn1::OctetStringRef::new(data)?.encode_value(encoder),
                    $name::Dict(dict) => common::encode_dict_body(dict, encoder),
                    $name::Array(array) => {
                        for value in array {
                            value.encode(encoder)?;
                        }

                        Ok(())
                    }
                    $($name::$var => ::der::asn1::ContextSpecificRef {
                        tag_number: ::der::TagNumber::$var_tag_num,
                        tag_mode: ::der::TagMode::Explicit,
                        value: &(),
                    }.encode_value(encoder),)*
                }
            }
        }
    };
}

def_owned_value!(
    /// Represents an Image4 property list value that may be found in a manifest or in a payload
    /// properties blob.
    ///
    /// For a borrowed `no_alloc` version see [`ValueRef`].
    #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
    #[cfg_attr(feature = "serde", serde(untagged, deny_unknown_fields))]
    Value,
    ValueRef,
    {data: #[cfg_attr(feature = "serde", serde(with = "serde_bytes"))]}
);

def_owned_value!(
    /// Represents an Image4 property list that may be found in an Apple-specific extension of
    /// X.509 certificates used to sign Image4 manifests.
    ///
    /// This is exactly the same type as [`Value`] with addition of the [`Constraint::Any`] and
    /// [`Constraint::Deny`] variants.
    ///
    /// For a borrowed `no_alloc` version see [`ConstraintRef`].
    Constraint,
    ConstraintRef,
    /// Matches any possible value.
    Any(N0),
    /// Never matches a value.
    Deny(N1)
);

impl Constraint {
    /// Checks that a value satisfies the constraint.
    ///
    /// For primitive values like [`Value::Boolean`] and arrays this basically means that the
    /// constraint should contain the same value of the same type or [`Constraint::Any`].
    /// Dictionaries should be a subset of the dictionary from the constraint.
    pub fn match_value(&self, value: &Value) -> bool {
        match (self, value) {
            (Self::Boolean(l), Value::Boolean(r)) => l == r,
            (Self::Integer(l), Value::Integer(r)) => l == r,
            (Self::Data(l), Value::Data(r)) => l == r,
            (Self::Array(l), Value::Array(r)) => {
                if l.len() != r.len() {
                    return false;
                }

                l.iter().zip(r.iter()).all(|(l, r)| l.match_value(r))
            }
            (Self::Dict(l), Value::Dict(r)) => l.iter().all(|(k, t)| {
                let is_denied = matches!(t, Self::Deny);

                let Some(v) = r.get(k) else {
                    return is_denied;
                };

                !is_denied && t.match_value(v)
            }),
            (Self::Any, _) => true,
            (Self::Deny, _) => false,
            _ => false,
        }
    }
}

impl From<Value> for Constraint {
    fn from(value: Value) -> Self {
        match value {
            Value::Boolean(v) => Constraint::Boolean(v),
            Value::Integer(v) => Constraint::Integer(v),
            Value::Data(v) => Constraint::Data(v),
            Value::Dict(v) => Constraint::Dict(
                v.into_iter()
                    .map(|(t, v)| (t, Constraint::from(v)))
                    .collect(),
            ),
            Value::Array(v) => Constraint::Array(v.into_iter().map(Constraint::from).collect()),
        }
    }
}

macro_rules! def_owned_collection {
    ($(#[$m:meta])* $name:ident, $borrowed:ident) => {
        #[derive(Clone, Debug)]
        #[cfg_attr(test, derive(Eq, PartialEq))]
        $(#[$m])*
        pub struct $name<V = Value> {
            pub(super) bytes: Vec<u8>,
            pub(super) header_length: Length,
            pub(super) length: Length,
            pub(super) _marker: ::core::marker::PhantomData<V>,
        }

        impl<V> $name<V> {
            #[doc = concat!("Returns a reference to the bytes wrapped by a ", stringify!($name))]
            pub fn as_bytes(&self) -> &[u8] {
                &self.bytes
            }
        }

        impl<'a, V: PropertyOwned> Decode<'a> for $name<V> {
            fn decode<R: Reader<'a>>(decoder: &mut R) -> der::Result<Self> {
                $borrowed::decode(decoder).map(From::from)
            }
        }

        impl<V> Encode for $name<V> {
            fn encoded_len(&self) -> der::Result<Length> {
                Ok(self.length)
            }

            fn encode(&self, encoder: &mut impl Writer) -> der::Result<()> {
                encoder.write(&self.bytes)
            }
        }

        impl<'a, V: PropertyOwned> From<$borrowed<'a, V::Ref<'a>>> for $name<V> {
            fn from(value: $borrowed<'a, V::Ref<'a>>) -> Self {
                (&value).into()
            }
        }

        impl<'a, V: PropertyOwned> From<&'_ $borrowed<'a, V::Ref<'a>>> for $name<V> {
            fn from(value: &'_ $borrowed<'a, V::Ref<'a>>) -> Self {
                Self {
                    bytes: value.bytes.to_vec(),
                    header_length: value.header_length,
                    length: value.length,
                    _marker: Default::default(),
                }
            }
        }

        impl<V: PropertyOwned> OwnedToRef for $name<V> {
            type Borrowed<'a> = $borrowed<'a, V::Ref<'a>> where V: 'a;

            fn owned_to_ref(&self) -> Self::Borrowed<'_> {
                self.into()
            }
        }
    }
}

def_owned_collection! {
    /// Holds an owned byte vector that could be decoded as a set of Image4 properties (aka a
    /// dictionary).
    ///
    /// # Usage
    ///
    /// This type is expected to be used as follows:
    ///
    /// 1. A DER set of Image4 properties is decoded into it using the [`Decode`] trait from the
    /// [`der`] crate;
    /// 2. The values inside are either parsed into a [`BTreeMap`] using the [`Dict::decode_owned`]
    /// method or ignored.
    ///
    /// [`Encode`] trait is also implemented so a [`Dict`] may be encoded back into DER without any
    /// serialization.
    ///
    /// # Validating the contents
    ///
    /// The contents of a dictionary aren't validated anyhow during decoding and may even be an
    /// invalid DER encoding. Currently the only way to validate the contents is by calling the
    /// [`Dict::decode_owned`] method.

    Dict, DictRef
}

impl<V: PropertyOwned> Dict<V> {
    /// Encodes a [`BTreeMap`] describing a dictionary of Image4 properties into a [`Dict`].
    pub fn encode_from(value: &BTreeMap<Tag, V>) -> der::Result<Self> {
        let body_length = common::encoded_dict_body_len(value)?;
        let header = Header {
            tag: der::Tag::Set,
            length: body_length,
        };
        let header_length = header.encoded_len()?;
        let length = (header_length + body_length)?;

        let mut bytes = alloc::vec![0; usize::try_from(length)?];
        let mut encoder = SliceWriter::new(&mut bytes);

        encoder.encode(&header)?;
        common::encode_dict_body(value, &mut encoder)?;

        Ok(Self {
            bytes,
            header_length,
            length,
            _marker: Default::default(),
        })
    }

    /// Decodes the contents of the body into an owned type.
    ///
    /// This function completely validates the contents and currently is the only way to do
    /// this.
    pub fn decode_owned(&self) -> der::Result<BTreeMap<Tag, V>> {
        DictRef::<V::Ref<'_>>::from(self).decode_owned()
    }
}

def_owned_collection! {
    /// Holds an owned byte vector that could be decoded as a sequence of Image4 properties (aka an
    /// array).
    ///
    /// # Usage
    ///
    /// This type is expected to be used as follows:
    ///
    /// 1. A DER sequence of Image4 properties is decoded into it using the [`Decode`] trait from
    /// the [`der`] crate;
    /// 2. The values inside are either parsed into a [`Vec`] using the [`Array::decode_owned`]
    /// method or ignored.
    ///
    /// [`Encode`] trait is also implemented so an [`Array`] may be encoded back into DER without any
    /// serialization.
    ///
    /// # Validating the contents
    ///
    /// The contents of an array aren't validated anyhow during decoding and may even be an invalid
    /// DER encoding. Currently the only way to validate the contents is by calling the
    /// [`Array::decode_owned`] method.

    Array, ArrayRef
}

impl<V: PropertyOwned> Array<V> {
    /// Encodes a [`Vec`] of Image4 property values into an [`Array`].
    pub fn encode_from(value: &Vec<V>) -> der::Result<Self> {
        let header = value.header()?;
        let mut bytes = Vec::new();
        value.encode_to_vec(&mut bytes)?;

        Ok(Self {
            bytes,
            header_length: header.encoded_len()?,
            length: header.length,
            _marker: Default::default(),
        })
    }

    /// Decodes the contents of the body into an owned type.
    ///
    /// This function completely validates the contents and currently is the only way to do
    /// this.
    pub fn decode_owned(&self) -> der::Result<Vec<V>> {
        ArrayRef::<V::Ref<'_>>::from(self).decode_owned()
    }
}