Skip to main content

hide_format/
codec.rs

1use minicbor::{Decoder, Encoder};
2
3use crate::{
4    FIRST_IGNORABLE_KEY, FormatError, MAX_EXTENSION_LEN, MAX_EXTENSIONS, MAX_HEADER_LEN,
5    MAX_METADATA_LEN, MAX_RECIPIENTS, MAX_SIGNATURES, MAX_STANZA_ITEMS, SUITE, TAG_LEN,
6};
7
8/// Stanza tag of the one recipient type HIDE/1.0 defines.
9const XWING_TAG: u64 = 1;
10const ENCAPSULATION_LEN: usize = 1120;
11const WRAPPED_CEK_LEN: usize = 48;
12
13#[derive(Clone, Debug, PartialEq, Eq)]
14pub struct RecipientStanza {
15    pub encapsulation: Vec<u8>,
16    pub wrapped_cek: Vec<u8>,
17}
18
19/// A recipient stanza of a type this implementation does not know. It is kept
20/// so the header re-encodes canonically and a signature can cover it, and it is
21/// skipped when looking for a key: a future recipient type must not make the
22/// file unreadable to the recipients it already had.
23#[derive(Clone, Debug, PartialEq, Eq)]
24pub struct UnknownStanza {
25    pub tag: u16,
26    pub fields: Vec<Vec<u8>>,
27}
28
29#[derive(Clone, Debug, PartialEq, Eq)]
30pub enum Stanza {
31    XWing(RecipientStanza),
32    Unknown(UnknownStanza),
33}
34
35impl Stanza {
36    pub fn tag(&self) -> u16 {
37        match self {
38            Self::XWing(_) => XWING_TAG as u16,
39            Self::Unknown(stanza) => stanza.tag,
40        }
41    }
42
43    /// The byte-string items after the tag, in wire order.
44    pub fn fields(&self) -> Vec<&[u8]> {
45        match self {
46            Self::XWing(stanza) => vec![&stanza.encapsulation, &stanza.wrapped_cek],
47            Self::Unknown(stanza) => stanza.fields.iter().map(Vec::as_slice).collect(),
48        }
49    }
50
51    pub fn as_xwing(&self) -> Option<&RecipientStanza> {
52        match self {
53            Self::XWing(stanza) => Some(stanza),
54            Self::Unknown(_) => None,
55        }
56    }
57}
58
59impl From<RecipientStanza> for Stanza {
60    fn from(stanza: RecipientStanza) -> Self {
61        Self::XWing(stanza)
62    }
63}
64
65/// An ignorable map entry: key 64..=65535, value an opaque byte string. A reader
66/// that does not know the key skips it; it is still authenticated and signed.
67#[derive(Clone, Debug, PartialEq, Eq)]
68pub struct Extension {
69    pub key: u16,
70    pub value: Vec<u8>,
71}
72
73/// A public signature over the container, readable by anyone holding the file.
74/// Confidential signatures live inside the encrypted metadata instead.
75#[derive(Clone, Debug, PartialEq, Eq)]
76pub struct SignatureStanza {
77    pub verifying_key: Vec<u8>,
78    pub signature: Vec<u8>,
79}
80
81pub const VERIFYING_KEY_LEN: usize = 1984;
82pub const SIGNATURE_LEN: usize = 3373;
83
84#[derive(Clone, Debug, PartialEq, Eq)]
85pub struct ProtectedHeader {
86    pub object_id: [u8; 32],
87    pub recipients: Vec<Stanza>,
88    pub encrypted_metadata: Vec<u8>,
89    /// Occupies the slot reserved as an empty array in v0.1. Empty here encodes
90    /// byte-for-byte as a v0.1 header, which is what keeps old files readable.
91    pub signatures: Vec<SignatureStanza>,
92    /// Ignorable keys after 5, ascending. Empty encodes exactly as HIDE/0.1.
93    pub extensions: Vec<Extension>,
94}
95
96impl ProtectedHeader {
97    pub fn encode(&self) -> Result<Vec<u8>, FormatError> {
98        self.encode_with_signatures(true)
99    }
100
101    /// The exact bytes a signature covers: the header with the signature slot
102    /// empty. Signing the slot that holds the signature would be circular.
103    pub fn signing_base(&self) -> Result<Vec<u8>, FormatError> {
104        self.encode_with_signatures(false)
105    }
106
107    fn encode_with_signatures(&self, include: bool) -> Result<Vec<u8>, FormatError> {
108        if self.recipients.is_empty() || self.recipients.len() > MAX_RECIPIENTS {
109            return Err(FormatError::MalformedHeader);
110        }
111        if !(TAG_LEN..=MAX_METADATA_LEN + TAG_LEN).contains(&self.encrypted_metadata.len()) {
112            return Err(FormatError::InvalidMetadata);
113        }
114        if self.signatures.len() > MAX_SIGNATURES {
115            return Err(FormatError::MalformedHeader);
116        }
117        check_extensions(&self.extensions).map_err(|_| FormatError::MalformedHeader)?;
118        let mut encoder = Encoder::new(Vec::new());
119        encoder
120            .map(5 + self.extensions.len() as u64)?
121            .u8(1)?
122            .u16(SUITE)?
123            .u8(2)?
124            .bytes(&self.object_id)?;
125        encoder.u8(3)?.array(self.recipients.len() as u64)?;
126        for stanza in &self.recipients {
127            encode_stanza(&mut encoder, stanza)?;
128        }
129        encoder.u8(4)?.bytes(&self.encrypted_metadata)?.u8(5)?;
130        let signatures: &[SignatureStanza] = if include { &self.signatures } else { &[] };
131        encoder.array(signatures.len() as u64)?;
132        for stanza in signatures {
133            if stanza.verifying_key.len() != VERIFYING_KEY_LEN
134                || stanza.signature.len() != SIGNATURE_LEN
135            {
136                return Err(FormatError::MalformedHeader);
137            }
138            encoder
139                .array(3)?
140                .u8(1)?
141                .bytes(&stanza.verifying_key)?
142                .bytes(&stanza.signature)?;
143        }
144        for extension in &self.extensions {
145            encoder.u16(extension.key)?.bytes(&extension.value)?;
146        }
147        let bytes = encoder.into_writer();
148        check_header_len(bytes.len())?;
149        Ok(bytes)
150    }
151
152    pub fn decode(bytes: &[u8]) -> Result<Self, FormatError> {
153        check_header_len(bytes.len())?;
154        let mut decoder = Decoder::new(bytes);
155        let entries = decoder.map()?.ok_or(FormatError::MalformedHeader)?;
156        if !(5..=5 + MAX_EXTENSIONS as u64).contains(&entries) {
157            return Err(FormatError::MalformedHeader);
158        }
159        key(&mut decoder, 1)?;
160        if decoder.u16()? != SUITE {
161            return Err(FormatError::UnsupportedSuite);
162        }
163        key(&mut decoder, 2)?;
164        let object_id = decoder
165            .bytes()?
166            .try_into()
167            .map_err(|_| FormatError::MalformedHeader)?;
168        key(&mut decoder, 3)?;
169        let count = decoder.array()?.ok_or(FormatError::MalformedHeader)?;
170        if count == 0 || count > MAX_RECIPIENTS as u64 {
171            return Err(FormatError::MalformedHeader);
172        }
173        let mut recipients = Vec::with_capacity(count as usize);
174        for _ in 0..count {
175            recipients.push(decode_stanza(&mut decoder)?);
176        }
177        key(&mut decoder, 4)?;
178        let metadata = decoder.bytes()?;
179        if !(TAG_LEN..=MAX_METADATA_LEN + TAG_LEN).contains(&metadata.len()) {
180            return Err(FormatError::InvalidMetadata);
181        }
182        key(&mut decoder, 5)?;
183        let signature_count = decoder.array()?.ok_or(FormatError::MalformedHeader)?;
184        if signature_count > MAX_SIGNATURES as u64 {
185            return Err(FormatError::MalformedHeader);
186        }
187        let mut signatures = Vec::with_capacity(signature_count as usize);
188        for _ in 0..signature_count {
189            signatures.push(decode_signature(&mut decoder)?);
190        }
191        let extensions =
192            decode_extensions(&mut decoder, entries - 5, 5).map_err(|error| match error {
193                FormatError::UnsupportedFeature => error,
194                _ => FormatError::MalformedHeader,
195            })?;
196        let header = Self {
197            object_id,
198            recipients,
199            encrypted_metadata: metadata.to_vec(),
200            signatures,
201            extensions,
202        };
203        canonical(bytes, decoder.position(), &header.encode()?)?;
204        Ok(header)
205    }
206}
207
208fn encode_stanza(encoder: &mut Encoder<Vec<u8>>, stanza: &Stanza) -> Result<(), FormatError> {
209    match stanza {
210        Stanza::XWing(stanza) => {
211            if stanza.encapsulation.len() != ENCAPSULATION_LEN
212                || stanza.wrapped_cek.len() != WRAPPED_CEK_LEN
213            {
214                return Err(FormatError::MalformedHeader);
215            }
216            encoder
217                .array(3)?
218                .u64(XWING_TAG)?
219                .bytes(&stanza.encapsulation)?
220                .bytes(&stanza.wrapped_cek)?;
221        }
222        Stanza::Unknown(stanza) => {
223            if u64::from(stanza.tag) <= XWING_TAG
224                || stanza.fields.len() >= MAX_STANZA_ITEMS
225                || stanza.fields.iter().any(|f| f.len() > MAX_EXTENSION_LEN)
226            {
227                return Err(FormatError::MalformedHeader);
228            }
229            encoder
230                .array(1 + stanza.fields.len() as u64)?
231                .u16(stanza.tag)?;
232            for field in &stanza.fields {
233                encoder.bytes(field)?;
234            }
235        }
236    }
237    Ok(())
238}
239
240fn decode_stanza(decoder: &mut Decoder<'_>) -> Result<Stanza, FormatError> {
241    let items = decoder.array()?.ok_or(FormatError::MalformedHeader)?;
242    if !(1..=MAX_STANZA_ITEMS as u64).contains(&items) {
243        return Err(FormatError::MalformedHeader);
244    }
245    let tag = decoder.u64()?;
246    if tag == XWING_TAG {
247        if items != 3 {
248            return Err(FormatError::MalformedHeader);
249        }
250        let encapsulation = decoder.bytes()?;
251        let wrapped_cek = decoder.bytes()?;
252        if encapsulation.len() != ENCAPSULATION_LEN || wrapped_cek.len() != WRAPPED_CEK_LEN {
253            return Err(FormatError::MalformedHeader);
254        }
255        return Ok(Stanza::XWing(RecipientStanza {
256            encapsulation: encapsulation.to_vec(),
257            wrapped_cek: wrapped_cek.to_vec(),
258        }));
259    }
260    let tag = u16::try_from(tag).map_err(|_| FormatError::MalformedHeader)?;
261    if tag == 0 {
262        return Err(FormatError::MalformedHeader);
263    }
264    let mut fields = Vec::new();
265    for _ in 1..items {
266        let field = decoder.bytes()?;
267        if field.len() > MAX_EXTENSION_LEN {
268            return Err(FormatError::MalformedHeader);
269        }
270        fields.push(field.to_vec());
271    }
272    Ok(Stanza::Unknown(UnknownStanza { tag, fields }))
273}
274
275/// Every rule an extension list must satisfy, on the way out as on the way in.
276fn check_extensions(extensions: &[Extension]) -> Result<(), FormatError> {
277    if extensions.len() > MAX_EXTENSIONS {
278        return Err(FormatError::MalformedHeader);
279    }
280    let mut previous = 0;
281    for extension in extensions {
282        let key = u64::from(extension.key);
283        if key < FIRST_IGNORABLE_KEY || key <= previous || extension.value.len() > MAX_EXTENSION_LEN
284        {
285            return Err(FormatError::MalformedHeader);
286        }
287        previous = key;
288    }
289    Ok(())
290}
291
292/// Reads `count` map entries after the core keys, the last of which was
293/// `last_core`. A key in the critical range 6..=63 is refused as
294/// `UnsupportedFeature`: 1.0 defines none, so no reader can honour one.
295fn decode_extensions(
296    decoder: &mut Decoder<'_>,
297    count: u64,
298    last_core: u64,
299) -> Result<Vec<Extension>, FormatError> {
300    let mut extensions = Vec::new();
301    let mut previous = last_core;
302    for _ in 0..count {
303        let key = decoder.u64()?;
304        if key <= previous {
305            return Err(FormatError::MalformedHeader);
306        }
307        if key < FIRST_IGNORABLE_KEY {
308            return Err(FormatError::UnsupportedFeature);
309        }
310        let key = u16::try_from(key).map_err(|_| FormatError::MalformedHeader)?;
311        let value = decoder.bytes()?;
312        if value.len() > MAX_EXTENSION_LEN {
313            return Err(FormatError::MalformedHeader);
314        }
315        previous = u64::from(key);
316        extensions.push(Extension {
317            key,
318            value: value.to_vec(),
319        });
320    }
321    Ok(extensions)
322}
323
324fn decode_signature(decoder: &mut Decoder<'_>) -> Result<SignatureStanza, FormatError> {
325    // The tag is read as u64 so a tag above 255 is an unsupported signature
326    // type rather than a malformed header. Spec 6.1 requires the two classes to
327    // be distinguishable, and the Node reader classifies both as unsupported.
328    if decoder.array()? != Some(3) || decoder.u64()? != 1 {
329        return Err(FormatError::UnsupportedFeature);
330    }
331    let verifying_key = decoder.bytes()?;
332    let signature = decoder.bytes()?;
333    if verifying_key.len() != VERIFYING_KEY_LEN || signature.len() != SIGNATURE_LEN {
334        return Err(FormatError::UnsupportedFeature);
335    }
336    Ok(SignatureStanza {
337        verifying_key: verifying_key.to_vec(),
338        signature: signature.to_vec(),
339    })
340}
341
342pub fn encode_header(protected: &[u8], mac: &[u8; 32]) -> Result<Vec<u8>, FormatError> {
343    check_header_len(protected.len())?;
344    let mut encoder = Encoder::new(Vec::new());
345    encoder.array(2)?.bytes(protected)?.bytes(mac)?;
346    let bytes = encoder.into_writer();
347    check_header_len(bytes.len())?;
348    Ok(bytes)
349}
350
351pub fn decode_header(bytes: &[u8]) -> Result<(Vec<u8>, [u8; 32]), FormatError> {
352    check_header_len(bytes.len())?;
353    let mut decoder = Decoder::new(bytes);
354    if decoder.array()? != Some(2) {
355        return Err(FormatError::MalformedHeader);
356    }
357    let protected = decoder.bytes()?;
358    let mac = decoder
359        .bytes()?
360        .try_into()
361        .map_err(|_| FormatError::MalformedHeader)?;
362    canonical(bytes, decoder.position(), &encode_header(protected, &mac)?)?;
363    Ok((protected.to_vec(), mac))
364}
365
366#[derive(Default, Clone, Debug, PartialEq, Eq)]
367pub struct Metadata {
368    pub filename: Option<String>,
369    pub media_type: Option<String>,
370    /// A signature visible only to recipients. Excluded from the signing base,
371    /// because it cannot cover itself.
372    pub signature: Option<SignatureStanza>,
373    /// Ignorable keys 64..=65535, ascending. Part of the signing base.
374    pub extensions: Vec<Extension>,
375}
376
377impl Metadata {
378    pub fn encode(&self) -> Result<Vec<u8>, FormatError> {
379        self.encode_with_signature(true)
380    }
381
382    /// The metadata as it looked before a signature was attached.
383    pub fn signing_base(&self) -> Result<Vec<u8>, FormatError> {
384        self.encode_with_signature(false)
385    }
386
387    fn encode_with_signature(&self, include: bool) -> Result<Vec<u8>, FormatError> {
388        let signature = if include {
389            self.signature.as_ref()
390        } else {
391            None
392        };
393        let mut encoder = Encoder::new(Vec::new());
394        check_extensions(&self.extensions).map_err(|_| FormatError::InvalidMetadata)?;
395        encoder.map(
396            u64::from(self.filename.is_some())
397                + u64::from(self.media_type.is_some())
398                + u64::from(signature.is_some())
399                + self.extensions.len() as u64,
400        )?;
401        if let Some(filename) = &self.filename {
402            validate_filename(filename)?;
403            encoder.u8(1)?.str(filename)?;
404        }
405        if let Some(media_type) = &self.media_type {
406            if media_type.is_empty()
407                || media_type.len() > 255
408                || !media_type.bytes().all(|byte| (32..=126).contains(&byte))
409            {
410                return Err(FormatError::InvalidMetadata);
411            }
412            encoder.u8(2)?.str(media_type)?;
413        }
414        if let Some(stanza) = signature {
415            if stanza.verifying_key.len() != VERIFYING_KEY_LEN
416                || stanza.signature.len() != SIGNATURE_LEN
417            {
418                return Err(FormatError::InvalidMetadata);
419            }
420            encoder
421                .u8(3)?
422                .array(3)?
423                .u8(1)?
424                .bytes(&stanza.verifying_key)?
425                .bytes(&stanza.signature)?;
426        }
427        for extension in &self.extensions {
428            encoder.u16(extension.key)?.bytes(&extension.value)?;
429        }
430        Ok(encoder.into_writer())
431    }
432
433    pub fn decode(bytes: &[u8]) -> Result<Self, FormatError> {
434        if bytes.len() > MAX_METADATA_LEN {
435            return Err(FormatError::InvalidMetadata);
436        }
437        let mut decoder = Decoder::new(bytes);
438        let count = decoder.map()?.ok_or(FormatError::InvalidMetadata)?;
439        if count > 3 + MAX_EXTENSIONS as u64 {
440            return Err(FormatError::InvalidMetadata);
441        }
442        let mut metadata = Self::default();
443        let mut previous = 0;
444        let mut remaining = count;
445        while remaining > 0 {
446            // Peek: a key past 3 starts the extension run, which must be last.
447            let mut probe = decoder.clone();
448            let field = probe.u64()?;
449            if field > 3 {
450                break;
451            }
452            decoder.u64()?;
453            remaining -= 1;
454            if field <= previous || field == 0 {
455                return Err(FormatError::InvalidMetadata);
456            }
457            previous = field;
458            if field == 3 {
459                // Keep the class the signature decoder chose: an unknown tag is
460                // an unsupported feature, which spec 6.1 requires to be told
461                // apart from a malformed metadata map.
462                metadata.signature = Some(decode_signature(&mut decoder)?);
463                continue;
464            }
465            let text = decoder.str()?;
466            if text.len() > 255 {
467                return Err(FormatError::InvalidMetadata);
468            }
469            match field {
470                1 => metadata.filename = Some(text.to_owned()),
471                2 => metadata.media_type = Some(text.to_owned()),
472                _ => return Err(FormatError::InvalidMetadata),
473            }
474        }
475        metadata.extensions =
476            decode_extensions(&mut decoder, remaining, previous).map_err(|error| match error {
477                FormatError::UnsupportedFeature => error,
478                _ => FormatError::InvalidMetadata,
479            })?;
480        canonical(bytes, decoder.position(), &metadata.encode()?)?;
481        Ok(metadata)
482    }
483}
484
485fn validate_filename(filename: &str) -> Result<(), FormatError> {
486    let stem = filename
487        .split('.')
488        .next()
489        .unwrap_or("")
490        .to_ascii_uppercase();
491    let reserved = matches!(stem.as_str(), "CON" | "PRN" | "AUX" | "NUL")
492        || (stem.len() == 4
493            && (stem.starts_with("COM") || stem.starts_with("LPT"))
494            && (b'1'..=b'9').contains(&stem.as_bytes()[3]));
495    if filename.is_empty()
496        || filename.len() > 255
497        || matches!(filename, "." | "..")
498        || filename.ends_with(['.', ' '])
499        || reserved
500        || filename
501            .chars()
502            .any(|character| character.is_control() || "<>:\"/\\|?*".contains(character))
503    {
504        return Err(FormatError::InvalidMetadata);
505    }
506    Ok(())
507}
508
509fn key(decoder: &mut Decoder<'_>, expected: u8) -> Result<(), FormatError> {
510    if decoder.u8()? != expected {
511        return Err(FormatError::MalformedHeader);
512    }
513    Ok(())
514}
515
516fn check_header_len(length: usize) -> Result<(), FormatError> {
517    if length == 0 || length > MAX_HEADER_LEN {
518        return Err(FormatError::HeaderTooLarge);
519    }
520    Ok(())
521}
522
523fn canonical(original: &[u8], consumed: usize, encoded: &[u8]) -> Result<(), FormatError> {
524    if consumed != original.len() || original != encoded {
525        return Err(FormatError::NonCanonical);
526    }
527    Ok(())
528}
529
530#[cfg(test)]
531mod tests {
532    use super::*;
533
534    fn header() -> ProtectedHeader {
535        ProtectedHeader {
536            object_id: [1; 32],
537            recipients: vec![Stanza::XWing(RecipientStanza {
538                encapsulation: vec![2; 1120],
539                wrapped_cek: vec![3; 48],
540            })],
541            encrypted_metadata: vec![4; 17],
542            signatures: Vec::new(),
543            extensions: Vec::new(),
544        }
545    }
546
547    #[test]
548    fn header_roundtrip_preserves_authenticated_bytes() -> Result<(), FormatError> {
549        let protected = header().encode()?;
550        assert_eq!(ProtectedHeader::decode(&protected)?, header());
551        assert_eq!(
552            decode_header(&encode_header(&protected, &[5; 32])?)?,
553            (protected, [5; 32])
554        );
555        Ok(())
556    }
557
558    fn signed_header() -> ProtectedHeader {
559        ProtectedHeader {
560            signatures: vec![SignatureStanza {
561                verifying_key: vec![6; VERIFYING_KEY_LEN],
562                signature: vec![7; SIGNATURE_LEN],
563            }],
564            ..header()
565        }
566    }
567
568    /// The compatibility invariant: an unsigned header must be byte-identical to
569    /// what v0.1 wrote, or every existing container stops opening.
570    #[test]
571    fn an_unsigned_header_still_ends_with_the_v0_1_empty_slot() -> Result<(), FormatError> {
572        let encoded = header().encode()?;
573        // 0x05 = key 5, 0x80 = CBOR array of length 0.
574        assert_eq!(&encoded[encoded.len() - 2..], &[0x05, 0x80]);
575        assert_eq!(header().signing_base()?, encoded);
576        Ok(())
577    }
578
579    #[test]
580    fn a_signed_header_survives_encoding() -> Result<(), FormatError> {
581        let encoded = signed_header().encode()?;
582        assert_eq!(ProtectedHeader::decode(&encoded)?, signed_header());
583        Ok(())
584    }
585
586    /// The signature covers the header with the slot empty, so adding a
587    /// signature must not disturb what earlier signers committed to.
588    #[test]
589    fn the_signing_base_excludes_the_signatures() -> Result<(), FormatError> {
590        assert_eq!(signed_header().signing_base()?, header().encode()?);
591        Ok(())
592    }
593
594    #[test]
595    fn a_malformed_signature_stanza_is_refused() {
596        for (key_len, sig_len) in [
597            (VERIFYING_KEY_LEN - 1, SIGNATURE_LEN),
598            (VERIFYING_KEY_LEN, SIGNATURE_LEN + 1),
599        ] {
600            let header = ProtectedHeader {
601                signatures: vec![SignatureStanza {
602                    verifying_key: vec![6; key_len],
603                    signature: vec![7; sig_len],
604                }],
605                ..header()
606            };
607            assert_eq!(header.encode(), Err(FormatError::MalformedHeader));
608        }
609    }
610
611    #[test]
612    fn too_many_signatures_are_refused() {
613        let header = ProtectedHeader {
614            signatures: vec![
615                SignatureStanza {
616                    verifying_key: vec![6; VERIFYING_KEY_LEN],
617                    signature: vec![7; SIGNATURE_LEN],
618                };
619                MAX_SIGNATURES + 1
620            ],
621            ..header()
622        };
623        assert_eq!(header.encode(), Err(FormatError::MalformedHeader));
624    }
625
626    // Only the first stanza is ever verified, so a second one on the wire would
627    // be a signature nobody checks. The decoder must refuse it, not skip it.
628    #[test]
629    fn a_second_signature_stanza_is_refused_on_the_wire() -> Result<(), FormatError> {
630        let stanza = SignatureStanza {
631            verifying_key: vec![6; VERIFYING_KEY_LEN],
632            signature: vec![7; SIGNATURE_LEN],
633        };
634        let one = ProtectedHeader {
635            signatures: vec![stanza.clone()],
636            ..header()
637        }
638        .encode()?;
639        assert!(ProtectedHeader::decode(&one).is_ok());
640
641        // The signature array is the last field, so its CBOR head is the last
642        // `array(1)` marker before the stanza. Rewrite it to `array(2)` and
643        // append a copy of the stanza, which is what encode() refuses to do.
644        let mut single = Encoder::new(Vec::new());
645        single
646            .array(3)?
647            .u8(1)?
648            .bytes(&stanza.verifying_key)?
649            .bytes(&stanza.signature)?;
650        let encoded_stanza = single.into_writer();
651        let stanza_at = one.len() - encoded_stanza.len();
652        assert_eq!(&one[stanza_at..], encoded_stanza.as_slice());
653        assert_eq!(
654            one[stanza_at - 1],
655            0x81,
656            "array(1) head precedes the stanza"
657        );
658        let mut two = one.clone();
659        two[stanza_at - 1] = 0x82;
660        two.extend_from_slice(&encoded_stanza);
661
662        assert_eq!(
663            ProtectedHeader::decode(&two),
664            Err(FormatError::MalformedHeader)
665        );
666        Ok(())
667    }
668
669    #[test]
670    fn metadata_has_exact_encoding() -> Result<(), FormatError> {
671        let metadata = Metadata {
672            filename: Some("hello.txt".into()),
673            ..Metadata::default()
674        };
675        assert_eq!(metadata.encode()?, b"\xa1\x01\x69hello.txt");
676        assert_eq!(Metadata::decode(b"\xa1\x01\x69hello.txt")?, metadata);
677        assert_eq!(Metadata::default().encode()?, [0xa0]);
678        Ok(())
679    }
680
681    #[test]
682    fn rejects_noncanonical_duplicate_unknown_and_indefinite() -> Result<(), FormatError> {
683        for bytes in [
684            b"\xa1\x18\x01\x61a".as_slice(),
685            b"\xbf\xff",
686            b"\xa2\x01\x61a\x01\x61b",
687            b"\xa1\x03\x61a",
688            b"\xa0\x00",
689            b"\xa1\x01\x7f\xff",
690            b"\xa1\x01\xc0\x61a",
691        ] {
692            assert!(Metadata::decode(bytes).is_err(), "{bytes:?}");
693        }
694        let original = header().encode()?;
695        let mut nonminimal = original.clone();
696        nonminimal.splice(2..3, [0x18, 1]);
697        assert_eq!(
698            ProtectedHeader::decode(&nonminimal),
699            Err(FormatError::NonCanonical)
700        );
701        let mut duplicate = original;
702        duplicate[3] = 1;
703        assert!(ProtectedHeader::decode(&duplicate).is_err());
704        Ok(())
705    }
706
707    #[test]
708    fn rejects_hostile_counts_and_every_truncated_header() -> Result<(), FormatError> {
709        let bytes = header().encode()?;
710        for length in 0..bytes.len() {
711            assert!(ProtectedHeader::decode(&bytes[..length]).is_err());
712        }
713        let mut oversized = header();
714        oversized.recipients = vec![oversized.recipients[0].clone(); MAX_RECIPIENTS + 1];
715        assert!(oversized.encode().is_err());
716        assert!(decode_header(&vec![0; MAX_HEADER_LEN + 1]).is_err());
717        assert!(ProtectedHeader::decode(b"\xa5\x01\x01\x02\x58\xff").is_err());
718        Ok(())
719    }
720
721    #[test]
722    fn rejects_nonportable_filenames() {
723        for filename in [
724            "",
725            ".",
726            "..",
727            "../a",
728            "a/b",
729            "a\\b",
730            "C:a",
731            "NUL.txt",
732            "com1",
733            "LPT9.pdf",
734            "file.",
735            "file ",
736            "line\nname",
737            "a*b",
738        ] {
739            assert!(
740                Metadata {
741                    filename: Some(filename.into()),
742                    ..Metadata::default()
743                }
744                .encode()
745                .is_err(),
746                "{filename:?}"
747            );
748        }
749    }
750}