Skip to main content

hide_format/
lib.rs

1use thiserror::Error;
2
3mod codec;
4pub use codec::{
5    Extension, Metadata, ProtectedHeader, RecipientStanza, SIGNATURE_LEN, SignatureStanza, Stanza,
6    UnknownStanza, VERIFYING_KEY_LEN, decode_header, encode_header,
7};
8
9pub const MAGIC: [u8; 8] = *b"HIDE\r\n\x1a\n";
10pub const PREAMBLE_LEN: usize = 16;
11pub const MAX_HEADER_LEN: usize = 1024 * 1024;
12pub const CHUNK_LEN: usize = 65_536;
13pub const SUITE: u16 = 1;
14pub const MAX_RECIPIENTS: usize = 64;
15/// Exactly one signer is verified, so exactly one stanza is admitted. Allowing
16/// more would let a recipient append stanzas nobody checks.
17pub const MAX_SIGNATURES: usize = 1;
18pub const MAX_METADATA_LEN: usize = 262_144;
19pub const TAG_LEN: usize = 16;
20/// The one flag HIDE/1.0 defines. Every flag bit is critical: a reader that
21/// does not know a set bit must refuse the container, never ignore the bit.
22pub const FLAG_SIGNED: u8 = 0x01;
23/// HIDE/0.5 through 0.8 marked a signed container by minor 2. Still read,
24/// never written, and only valid with no flags set.
25pub const LEGACY_SIGNED_MINOR: u8 = 2;
26/// The minor a HIDE/1.0 writer emits. A minor is a non-breaking revision, so
27/// readers accept every minor except 0 and the legacy 2.
28pub const CURRENT_MINOR: u8 = 1;
29/// Ignorable extensions: at most this many per map, each value at most this long.
30pub const MAX_EXTENSIONS: usize = 16;
31pub const MAX_EXTENSION_LEN: usize = 65_536;
32/// Keys below this are core (1..=5) or critical (6..=63); at or above it,
33/// up to `u16::MAX`, a reader that does not know the key skips it.
34pub const FIRST_IGNORABLE_KEY: u64 = 64;
35/// A recipient stanza is a tag followed by at most seven byte strings.
36pub const MAX_STANZA_ITEMS: usize = 8;
37
38#[derive(Debug, Error, PartialEq, Eq)]
39pub enum FormatError {
40    #[error("malformed HIDE header")]
41    MalformedHeader,
42    #[error("noncanonical CBOR encoding")]
43    NonCanonical,
44    #[error("unsupported cryptographic suite")]
45    UnsupportedSuite,
46    #[error("invalid file metadata")]
47    InvalidMetadata,
48    #[error("invalid HIDE container")]
49    InvalidContainer,
50    #[error("unsupported HIDE version")]
51    UnsupportedVersion,
52    #[error("unsupported HIDE object kind or flags")]
53    UnsupportedFeature,
54    #[error("header length is outside protocol limits")]
55    HeaderTooLarge,
56}
57
58impl From<minicbor::decode::Error> for FormatError {
59    fn from(_: minicbor::decode::Error) -> Self {
60        Self::MalformedHeader
61    }
62}
63
64impl From<minicbor::encode::Error<core::convert::Infallible>> for FormatError {
65    fn from(_: minicbor::encode::Error<core::convert::Infallible>) -> Self {
66        Self::MalformedHeader
67    }
68}
69
70#[derive(Debug, Clone, Copy, PartialEq, Eq)]
71pub struct Preamble {
72    header_len: u32,
73    minor: u8,
74    flags: u8,
75}
76
77impl Preamble {
78    pub fn new(header_len: usize) -> Result<Self, FormatError> {
79        Self::with_signed(header_len, false)
80    }
81
82    /// A signed container sets the critical SIGNED flag, so a reader that does
83    /// not implement signatures refuses it rather than ignoring the signature.
84    pub fn with_signed(header_len: usize, signed: bool) -> Result<Self, FormatError> {
85        let flags = if signed { FLAG_SIGNED } else { 0 };
86        Self::from_parts(header_len, CURRENT_MINOR, flags)
87    }
88
89    /// The HIDE/0.5 form of a signed container. Readers still accept it; only
90    /// test code writes it, to prove that they do.
91    pub fn legacy_signed(header_len: usize) -> Result<Self, FormatError> {
92        Self::from_parts(header_len, LEGACY_SIGNED_MINOR, 0)
93    }
94
95    /// Validates exactly as [`Preamble::decode`] does.
96    pub fn from_parts(header_len: usize, minor: u8, flags: u8) -> Result<Self, FormatError> {
97        if minor == 0 {
98            return Err(FormatError::UnsupportedVersion);
99        }
100        if flags & !FLAG_SIGNED != 0 || (minor == LEGACY_SIGNED_MINOR && flags != 0) {
101            return Err(FormatError::UnsupportedFeature);
102        }
103        if header_len == 0 || header_len > MAX_HEADER_LEN {
104            return Err(FormatError::HeaderTooLarge);
105        }
106        Ok(Self {
107            header_len: header_len as u32,
108            minor,
109            flags,
110        })
111    }
112
113    pub fn header_len(self) -> usize {
114        self.header_len as usize
115    }
116
117    pub fn minor(self) -> u8 {
118        self.minor
119    }
120
121    pub fn flags(self) -> u8 {
122        self.flags
123    }
124
125    pub fn is_signed(self) -> bool {
126        self.is_legacy() || self.flags & FLAG_SIGNED != 0
127    }
128
129    /// A HIDE/0.5–0.8 signed container: legacy transcript, no extensions.
130    pub fn is_legacy(self) -> bool {
131        self.minor == LEGACY_SIGNED_MINOR
132    }
133
134    /// Magic, major, minor, kind and flags: everything but the header length,
135    /// which a signature cannot cover because the signature is in the header.
136    pub fn signed_prefix(self) -> [u8; 12] {
137        let mut prefix = [0; 12];
138        prefix.copy_from_slice(&self.encode()[..12]);
139        prefix
140    }
141
142    pub fn encode(self) -> [u8; PREAMBLE_LEN] {
143        let mut bytes = [0; PREAMBLE_LEN];
144        bytes[..8].copy_from_slice(&MAGIC);
145        bytes[9] = self.minor;
146        bytes[10] = 1;
147        bytes[11] = self.flags;
148        bytes[12..].copy_from_slice(&self.header_len.to_be_bytes());
149        bytes
150    }
151
152    pub fn decode(bytes: &[u8]) -> Result<Self, FormatError> {
153        if bytes.len() != PREAMBLE_LEN || bytes[..8] != MAGIC {
154            return Err(FormatError::InvalidContainer);
155        }
156        if bytes[8] != 0 {
157            return Err(FormatError::UnsupportedVersion);
158        }
159        if bytes[10] != 1 {
160            return Err(FormatError::UnsupportedFeature);
161        }
162        let length = u32::from_be_bytes([bytes[12], bytes[13], bytes[14], bytes[15]]);
163        let length = usize::try_from(length).map_err(|_| FormatError::HeaderTooLarge)?;
164        Self::from_parts(length, bytes[9], bytes[11])
165    }
166}
167
168#[cfg(test)]
169mod tests {
170    use super::*;
171
172    #[test]
173    fn preamble_has_exact_wire_encoding() -> Result<(), FormatError> {
174        let preamble = Preamble::new(0x1234)?;
175        assert_eq!(
176            preamble.encode(),
177            [
178                0x48, 0x49, 0x44, 0x45, 13, 10, 26, 10, 0, 1, 1, 0, 0, 0, 0x12, 0x34
179            ]
180        );
181        assert_eq!(Preamble::decode(&preamble.encode())?, preamble);
182        Ok(())
183    }
184
185    #[test]
186    fn rejects_every_truncated_preamble() -> Result<(), FormatError> {
187        let bytes = Preamble::new(128)?.encode();
188        for length in 0..PREAMBLE_LEN {
189            assert_eq!(
190                Preamble::decode(&bytes[..length]),
191                Err(FormatError::InvalidContainer)
192            );
193        }
194        Ok(())
195    }
196
197    #[test]
198    fn rejects_unknown_version_kind_flags_and_bad_magic() -> Result<(), FormatError> {
199        let original = Preamble::new(128)?.encode();
200        // Byte 9, the minor, is left out: a minor is a non-breaking revision and
201        // flipping its high bit yields a minor every reader must accept.
202        for offset in (0..12).filter(|&offset| offset != 9) {
203            let mut bytes = original;
204            bytes[offset] ^= 0x80;
205            assert!(Preamble::decode(&bytes).is_err(), "offset {offset}");
206        }
207        Ok(())
208    }
209
210    fn with(minor: u8, flags: u8) -> [u8; PREAMBLE_LEN] {
211        let mut bytes = Preamble::new(128).expect("valid length").encode();
212        bytes[9] = minor;
213        bytes[11] = flags;
214        bytes
215    }
216
217    #[test]
218    fn every_minor_but_zero_is_a_readable_revision() -> Result<(), FormatError> {
219        for minor in [1, 3, 7, 0x80, 0xff] {
220            let preamble = Preamble::decode(&with(minor, 0))?;
221            assert_eq!(preamble.minor(), minor);
222            assert!(
223                !preamble.is_signed() && !preamble.is_legacy(),
224                "minor {minor}"
225            );
226        }
227        assert_eq!(
228            Preamble::decode(&with(0, 0)),
229            Err(FormatError::UnsupportedVersion)
230        );
231        Ok(())
232    }
233
234    /// Every flag is critical. An unknown bit, or any flag on the legacy minor,
235    /// must refuse the container rather than be ignored.
236    #[test]
237    fn flags_are_critical_and_signed_is_the_only_known_one() -> Result<(), FormatError> {
238        let signed = Preamble::decode(&with(1, FLAG_SIGNED))?;
239        assert!(signed.is_signed() && !signed.is_legacy());
240        assert!(Preamble::decode(&with(9, FLAG_SIGNED))?.is_signed());
241        for flags in [0x02, 0x04, 0x80, 0x03, 0xff] {
242            assert_eq!(
243                Preamble::decode(&with(1, flags)),
244                Err(FormatError::UnsupportedFeature),
245                "flags {flags:#04x}"
246            );
247        }
248        assert_eq!(
249            Preamble::decode(&with(LEGACY_SIGNED_MINOR, FLAG_SIGNED)),
250            Err(FormatError::UnsupportedFeature)
251        );
252        Ok(())
253    }
254
255    #[test]
256    fn legacy_minor_two_reads_as_signed_and_is_never_written() -> Result<(), FormatError> {
257        let legacy = Preamble::decode(&with(LEGACY_SIGNED_MINOR, 0))?;
258        assert!(legacy.is_signed() && legacy.is_legacy());
259        let written = Preamble::with_signed(128, true)?.encode();
260        assert_eq!((written[9], written[11]), (CURRENT_MINOR, FLAG_SIGNED));
261        // Unsigned 1.0 output stays byte-identical to HIDE/0.1.
262        assert_eq!(&Preamble::new(128)?.encode()[8..12], &[0, 1, 1, 0]);
263        Ok(())
264    }
265
266    #[test]
267    fn rejects_hostile_length_before_allocation() -> Result<(), FormatError> {
268        assert!(Preamble::new(MAX_HEADER_LEN).is_ok());
269        assert_eq!(Preamble::new(0), Err(FormatError::HeaderTooLarge));
270        assert_eq!(
271            Preamble::new(MAX_HEADER_LEN + 1),
272            Err(FormatError::HeaderTooLarge)
273        );
274        let mut bytes = Preamble::new(128)?.encode();
275        bytes[12..].copy_from_slice(&u32::MAX.to_be_bytes());
276        assert_eq!(Preamble::decode(&bytes), Err(FormatError::HeaderTooLarge));
277        Ok(())
278    }
279}