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    if decoder.array()? != Some(3) || decoder.u8()? != 1 {
326        return Err(FormatError::UnsupportedFeature);
327    }
328    let verifying_key = decoder.bytes()?;
329    let signature = decoder.bytes()?;
330    if verifying_key.len() != VERIFYING_KEY_LEN || signature.len() != SIGNATURE_LEN {
331        return Err(FormatError::MalformedHeader);
332    }
333    Ok(SignatureStanza {
334        verifying_key: verifying_key.to_vec(),
335        signature: signature.to_vec(),
336    })
337}
338
339pub fn encode_header(protected: &[u8], mac: &[u8; 32]) -> Result<Vec<u8>, FormatError> {
340    check_header_len(protected.len())?;
341    let mut encoder = Encoder::new(Vec::new());
342    encoder.array(2)?.bytes(protected)?.bytes(mac)?;
343    let bytes = encoder.into_writer();
344    check_header_len(bytes.len())?;
345    Ok(bytes)
346}
347
348pub fn decode_header(bytes: &[u8]) -> Result<(Vec<u8>, [u8; 32]), FormatError> {
349    check_header_len(bytes.len())?;
350    let mut decoder = Decoder::new(bytes);
351    if decoder.array()? != Some(2) {
352        return Err(FormatError::MalformedHeader);
353    }
354    let protected = decoder.bytes()?;
355    let mac = decoder
356        .bytes()?
357        .try_into()
358        .map_err(|_| FormatError::MalformedHeader)?;
359    canonical(bytes, decoder.position(), &encode_header(protected, &mac)?)?;
360    Ok((protected.to_vec(), mac))
361}
362
363#[derive(Default, Clone, Debug, PartialEq, Eq)]
364pub struct Metadata {
365    pub filename: Option<String>,
366    pub media_type: Option<String>,
367    /// A signature visible only to recipients. Excluded from the signing base,
368    /// because it cannot cover itself.
369    pub signature: Option<SignatureStanza>,
370    /// Ignorable keys 64..=65535, ascending. Part of the signing base.
371    pub extensions: Vec<Extension>,
372}
373
374impl Metadata {
375    pub fn encode(&self) -> Result<Vec<u8>, FormatError> {
376        self.encode_with_signature(true)
377    }
378
379    /// The metadata as it looked before a signature was attached.
380    pub fn signing_base(&self) -> Result<Vec<u8>, FormatError> {
381        self.encode_with_signature(false)
382    }
383
384    fn encode_with_signature(&self, include: bool) -> Result<Vec<u8>, FormatError> {
385        let signature = if include {
386            self.signature.as_ref()
387        } else {
388            None
389        };
390        let mut encoder = Encoder::new(Vec::new());
391        check_extensions(&self.extensions).map_err(|_| FormatError::InvalidMetadata)?;
392        encoder.map(
393            u64::from(self.filename.is_some())
394                + u64::from(self.media_type.is_some())
395                + u64::from(signature.is_some())
396                + self.extensions.len() as u64,
397        )?;
398        if let Some(filename) = &self.filename {
399            validate_filename(filename)?;
400            encoder.u8(1)?.str(filename)?;
401        }
402        if let Some(media_type) = &self.media_type {
403            if media_type.is_empty()
404                || media_type.len() > 255
405                || !media_type.bytes().all(|byte| (32..=126).contains(&byte))
406            {
407                return Err(FormatError::InvalidMetadata);
408            }
409            encoder.u8(2)?.str(media_type)?;
410        }
411        if let Some(stanza) = signature {
412            if stanza.verifying_key.len() != VERIFYING_KEY_LEN
413                || stanza.signature.len() != SIGNATURE_LEN
414            {
415                return Err(FormatError::InvalidMetadata);
416            }
417            encoder
418                .u8(3)?
419                .array(3)?
420                .u8(1)?
421                .bytes(&stanza.verifying_key)?
422                .bytes(&stanza.signature)?;
423        }
424        for extension in &self.extensions {
425            encoder.u16(extension.key)?.bytes(&extension.value)?;
426        }
427        Ok(encoder.into_writer())
428    }
429
430    pub fn decode(bytes: &[u8]) -> Result<Self, FormatError> {
431        if bytes.len() > MAX_METADATA_LEN {
432            return Err(FormatError::InvalidMetadata);
433        }
434        let mut decoder = Decoder::new(bytes);
435        let count = decoder.map()?.ok_or(FormatError::InvalidMetadata)?;
436        if count > 3 + MAX_EXTENSIONS as u64 {
437            return Err(FormatError::InvalidMetadata);
438        }
439        let mut metadata = Self::default();
440        let mut previous = 0;
441        let mut remaining = count;
442        while remaining > 0 {
443            // Peek: a key past 3 starts the extension run, which must be last.
444            let mut probe = decoder.clone();
445            let field = probe.u64()?;
446            if field > 3 {
447                break;
448            }
449            decoder.u64()?;
450            remaining -= 1;
451            if field <= previous || field == 0 {
452                return Err(FormatError::InvalidMetadata);
453            }
454            previous = field;
455            if field == 3 {
456                metadata.signature =
457                    Some(decode_signature(&mut decoder).map_err(|_| FormatError::InvalidMetadata)?);
458                continue;
459            }
460            let text = decoder.str()?;
461            if text.len() > 255 {
462                return Err(FormatError::InvalidMetadata);
463            }
464            match field {
465                1 => metadata.filename = Some(text.to_owned()),
466                2 => metadata.media_type = Some(text.to_owned()),
467                _ => return Err(FormatError::InvalidMetadata),
468            }
469        }
470        metadata.extensions =
471            decode_extensions(&mut decoder, remaining, previous).map_err(|error| match error {
472                FormatError::UnsupportedFeature => error,
473                _ => FormatError::InvalidMetadata,
474            })?;
475        canonical(bytes, decoder.position(), &metadata.encode()?)?;
476        Ok(metadata)
477    }
478}
479
480fn validate_filename(filename: &str) -> Result<(), FormatError> {
481    let stem = filename
482        .split('.')
483        .next()
484        .unwrap_or("")
485        .to_ascii_uppercase();
486    let reserved = matches!(stem.as_str(), "CON" | "PRN" | "AUX" | "NUL")
487        || (stem.len() == 4
488            && (stem.starts_with("COM") || stem.starts_with("LPT"))
489            && (b'1'..=b'9').contains(&stem.as_bytes()[3]));
490    if filename.is_empty()
491        || filename.len() > 255
492        || matches!(filename, "." | "..")
493        || filename.ends_with(['.', ' '])
494        || reserved
495        || filename
496            .chars()
497            .any(|character| character.is_control() || "<>:\"/\\|?*".contains(character))
498    {
499        return Err(FormatError::InvalidMetadata);
500    }
501    Ok(())
502}
503
504fn key(decoder: &mut Decoder<'_>, expected: u8) -> Result<(), FormatError> {
505    if decoder.u8()? != expected {
506        return Err(FormatError::MalformedHeader);
507    }
508    Ok(())
509}
510
511fn check_header_len(length: usize) -> Result<(), FormatError> {
512    if length == 0 || length > MAX_HEADER_LEN {
513        return Err(FormatError::HeaderTooLarge);
514    }
515    Ok(())
516}
517
518fn canonical(original: &[u8], consumed: usize, encoded: &[u8]) -> Result<(), FormatError> {
519    if consumed != original.len() || original != encoded {
520        return Err(FormatError::NonCanonical);
521    }
522    Ok(())
523}
524
525#[cfg(test)]
526mod tests {
527    use super::*;
528
529    fn header() -> ProtectedHeader {
530        ProtectedHeader {
531            object_id: [1; 32],
532            recipients: vec![Stanza::XWing(RecipientStanza {
533                encapsulation: vec![2; 1120],
534                wrapped_cek: vec![3; 48],
535            })],
536            encrypted_metadata: vec![4; 17],
537            signatures: Vec::new(),
538            extensions: Vec::new(),
539        }
540    }
541
542    #[test]
543    fn header_roundtrip_preserves_authenticated_bytes() -> Result<(), FormatError> {
544        let protected = header().encode()?;
545        assert_eq!(ProtectedHeader::decode(&protected)?, header());
546        assert_eq!(
547            decode_header(&encode_header(&protected, &[5; 32])?)?,
548            (protected, [5; 32])
549        );
550        Ok(())
551    }
552
553    fn signed_header() -> ProtectedHeader {
554        ProtectedHeader {
555            signatures: vec![SignatureStanza {
556                verifying_key: vec![6; VERIFYING_KEY_LEN],
557                signature: vec![7; SIGNATURE_LEN],
558            }],
559            ..header()
560        }
561    }
562
563    /// The compatibility invariant: an unsigned header must be byte-identical to
564    /// what v0.1 wrote, or every existing container stops opening.
565    #[test]
566    fn an_unsigned_header_still_ends_with_the_v0_1_empty_slot() -> Result<(), FormatError> {
567        let encoded = header().encode()?;
568        // 0x05 = key 5, 0x80 = CBOR array of length 0.
569        assert_eq!(&encoded[encoded.len() - 2..], &[0x05, 0x80]);
570        assert_eq!(header().signing_base()?, encoded);
571        Ok(())
572    }
573
574    #[test]
575    fn a_signed_header_survives_encoding() -> Result<(), FormatError> {
576        let encoded = signed_header().encode()?;
577        assert_eq!(ProtectedHeader::decode(&encoded)?, signed_header());
578        Ok(())
579    }
580
581    /// The signature covers the header with the slot empty, so adding a
582    /// signature must not disturb what earlier signers committed to.
583    #[test]
584    fn the_signing_base_excludes_the_signatures() -> Result<(), FormatError> {
585        assert_eq!(signed_header().signing_base()?, header().encode()?);
586        Ok(())
587    }
588
589    #[test]
590    fn a_malformed_signature_stanza_is_refused() {
591        for (key_len, sig_len) in [
592            (VERIFYING_KEY_LEN - 1, SIGNATURE_LEN),
593            (VERIFYING_KEY_LEN, SIGNATURE_LEN + 1),
594        ] {
595            let header = ProtectedHeader {
596                signatures: vec![SignatureStanza {
597                    verifying_key: vec![6; key_len],
598                    signature: vec![7; sig_len],
599                }],
600                ..header()
601            };
602            assert_eq!(header.encode(), Err(FormatError::MalformedHeader));
603        }
604    }
605
606    #[test]
607    fn too_many_signatures_are_refused() {
608        let header = ProtectedHeader {
609            signatures: vec![
610                SignatureStanza {
611                    verifying_key: vec![6; VERIFYING_KEY_LEN],
612                    signature: vec![7; SIGNATURE_LEN],
613                };
614                MAX_SIGNATURES + 1
615            ],
616            ..header()
617        };
618        assert_eq!(header.encode(), Err(FormatError::MalformedHeader));
619    }
620
621    // Only the first stanza is ever verified, so a second one on the wire would
622    // be a signature nobody checks. The decoder must refuse it, not skip it.
623    #[test]
624    fn a_second_signature_stanza_is_refused_on_the_wire() -> Result<(), FormatError> {
625        let stanza = SignatureStanza {
626            verifying_key: vec![6; VERIFYING_KEY_LEN],
627            signature: vec![7; SIGNATURE_LEN],
628        };
629        let one = ProtectedHeader {
630            signatures: vec![stanza.clone()],
631            ..header()
632        }
633        .encode()?;
634        assert!(ProtectedHeader::decode(&one).is_ok());
635
636        // The signature array is the last field, so its CBOR head is the last
637        // `array(1)` marker before the stanza. Rewrite it to `array(2)` and
638        // append a copy of the stanza, which is what encode() refuses to do.
639        let mut single = Encoder::new(Vec::new());
640        single
641            .array(3)?
642            .u8(1)?
643            .bytes(&stanza.verifying_key)?
644            .bytes(&stanza.signature)?;
645        let encoded_stanza = single.into_writer();
646        let stanza_at = one.len() - encoded_stanza.len();
647        assert_eq!(&one[stanza_at..], encoded_stanza.as_slice());
648        assert_eq!(
649            one[stanza_at - 1],
650            0x81,
651            "array(1) head precedes the stanza"
652        );
653        let mut two = one.clone();
654        two[stanza_at - 1] = 0x82;
655        two.extend_from_slice(&encoded_stanza);
656
657        assert_eq!(
658            ProtectedHeader::decode(&two),
659            Err(FormatError::MalformedHeader)
660        );
661        Ok(())
662    }
663
664    #[test]
665    fn metadata_has_exact_encoding() -> Result<(), FormatError> {
666        let metadata = Metadata {
667            filename: Some("hello.txt".into()),
668            ..Metadata::default()
669        };
670        assert_eq!(metadata.encode()?, b"\xa1\x01\x69hello.txt");
671        assert_eq!(Metadata::decode(b"\xa1\x01\x69hello.txt")?, metadata);
672        assert_eq!(Metadata::default().encode()?, [0xa0]);
673        Ok(())
674    }
675
676    #[test]
677    fn rejects_noncanonical_duplicate_unknown_and_indefinite() -> Result<(), FormatError> {
678        for bytes in [
679            b"\xa1\x18\x01\x61a".as_slice(),
680            b"\xbf\xff",
681            b"\xa2\x01\x61a\x01\x61b",
682            b"\xa1\x03\x61a",
683            b"\xa0\x00",
684            b"\xa1\x01\x7f\xff",
685            b"\xa1\x01\xc0\x61a",
686        ] {
687            assert!(Metadata::decode(bytes).is_err(), "{bytes:?}");
688        }
689        let original = header().encode()?;
690        let mut nonminimal = original.clone();
691        nonminimal.splice(2..3, [0x18, 1]);
692        assert_eq!(
693            ProtectedHeader::decode(&nonminimal),
694            Err(FormatError::NonCanonical)
695        );
696        let mut duplicate = original;
697        duplicate[3] = 1;
698        assert!(ProtectedHeader::decode(&duplicate).is_err());
699        Ok(())
700    }
701
702    #[test]
703    fn rejects_hostile_counts_and_every_truncated_header() -> Result<(), FormatError> {
704        let bytes = header().encode()?;
705        for length in 0..bytes.len() {
706            assert!(ProtectedHeader::decode(&bytes[..length]).is_err());
707        }
708        let mut oversized = header();
709        oversized.recipients = vec![oversized.recipients[0].clone(); MAX_RECIPIENTS + 1];
710        assert!(oversized.encode().is_err());
711        assert!(decode_header(&vec![0; MAX_HEADER_LEN + 1]).is_err());
712        assert!(ProtectedHeader::decode(b"\xa5\x01\x01\x02\x58\xff").is_err());
713        Ok(())
714    }
715
716    #[test]
717    fn rejects_nonportable_filenames() {
718        for filename in [
719            "",
720            ".",
721            "..",
722            "../a",
723            "a/b",
724            "a\\b",
725            "C:a",
726            "NUL.txt",
727            "com1",
728            "LPT9.pdf",
729            "file.",
730            "file ",
731            "line\nname",
732            "a*b",
733        ] {
734            assert!(
735                Metadata {
736                    filename: Some(filename.into()),
737                    ..Metadata::default()
738                }
739                .encode()
740                .is_err(),
741                "{filename:?}"
742            );
743        }
744    }
745}