Skip to main content

embark_format/
entry.rs

1#[cfg(feature = "dec")]
2use crate::Result;
3use crate::{CodecId, CryptoId};
4#[cfg(feature = "enc")]
5use alloc::vec::Vec;
6
7/// The decoded header of one on-binary entry, as returned by
8/// [`read_header`].
9///
10/// `#[non_exhaustive]`: the on-binary layout is expected to grow (a
11/// content hash, per-entry flags), so fields get added over time. Read the
12/// fields you need; do not build one by hand or match it exhaustively.
13#[non_exhaustive]
14#[derive(Debug, Clone, Copy, PartialEq, Eq)]
15pub struct Header {
16    /// The compression applied to the payload.
17    pub codec: CodecId,
18    /// The AEAD cipher the payload was sealed with, if any.
19    pub crypto: CryptoId,
20    /// Length of the file *before* compression and encryption, in bytes.
21    ///
22    /// Decoders use it to size the output buffer, so it comes from
23    /// untrusted bytes and must be treated as a claim rather than a fact:
24    /// reserve fallibly, and check the decoded length against it.
25    pub orig_len: u64,
26    /// The AEAD nonce, present exactly when `crypto` is not
27    /// [`CryptoId::None`]. Stored in the clear, and unique per entry.
28    pub nonce: Option<[u8; 12]>,
29    /// The detached AEAD authentication tag, present under the same
30    /// condition as `nonce`.
31    pub tag: Option<[u8; 16]>,
32    /// Offset into the entry at which the payload begins, that is the
33    /// length of the header this `Header` was parsed from.
34    pub payload_offset: usize,
35    /// Length of the leading bytes -- the tag byte and the length varint --
36    /// that a sealed entry's AEAD tag covers as associated data, so that the
37    /// codec, cipher and claimed length cannot be rewritten under a tag that
38    /// still verifies. `entry[..aad_len]` is what to hand the cipher.
39    pub aad_len: usize,
40}
41
42/// Appends the part of the header every entry has -- the tag byte and the
43/// length varint -- to `out`.
44///
45/// These are also the bytes a sealed entry's AEAD tag covers as associated
46/// data, which is why they are reachable on their own: whoever seals a
47/// payload writes them first, hands them to the cipher, and then writes the
48/// entry with [`write_entry`], which produces the same bytes again.
49#[cfg(feature = "enc")]
50pub fn write_header(out: &mut Vec<u8>, codec: CodecId, crypto: CryptoId, orig_len: u64) {
51    out.push(codec.as_u8() | (crypto.as_u8() << 4));
52    crate::write_varint(out, orig_len);
53}
54
55/// Appends one complete entry -- header followed by `payload` -- to `out`.
56///
57/// `orig_len` is the length of the file before compression, and `nonce_tag`
58/// carries the AEAD nonce and tag when the payload was sealed. Pass `None`
59/// for a plaintext entry; `crypto` and `nonce_tag` have to agree, since
60/// [`read_header`] decides whether to expect the 28 nonce-and-tag bytes from
61/// `crypto` alone.
62#[cfg(feature = "enc")]
63pub fn write_entry(
64    out: &mut Vec<u8>,
65    codec: CodecId,
66    crypto: CryptoId,
67    orig_len: u64,
68    nonce_tag: Option<([u8; 12], [u8; 16])>,
69    payload: &[u8],
70) {
71    write_header(out, codec, crypto, orig_len);
72    if let Some((nonce, tag)) = nonce_tag {
73        out.extend_from_slice(&nonce);
74        out.extend_from_slice(&tag);
75    }
76    out.extend_from_slice(payload);
77}
78
79/// Parses the header at the front of `entry`.
80///
81/// Only the header is examined; the payload is left to the caller, which
82/// finds it at [`Header::payload_offset`]. Nothing is copied out of the
83/// payload and no allocation happens here, so this is cheap enough to call
84/// just to read [`Header::orig_len`].
85///
86/// # Errors
87///
88/// Returns [`Error::Truncated`](crate::Error::Truncated) if `entry` is
89/// shorter than the header it declares, [`Error::Corrupt`](crate::Error::Corrupt)
90/// if the length varint is malformed, and
91/// [`Error::UnknownCodec`](crate::Error::UnknownCodec) or
92/// [`Error::UnknownCrypto`](crate::Error::UnknownCrypto) if the tag byte
93/// names an unassigned id.
94#[cfg(feature = "dec")]
95pub fn read_header(entry: &[u8]) -> Result<Header> {
96    let tag_byte = *entry.first().ok_or(crate::Error::Truncated)?;
97    let codec = CodecId::from_u8(tag_byte & 0x0f)?;
98    let crypto = CryptoId::from_u8(tag_byte >> 4)?;
99    let (orig_len, used) = crate::read_varint(&entry[1..])?;
100    let mut offset = 1 + used;
101
102    let (nonce, tag) = match crypto {
103        CryptoId::None => (None, None),
104        // Both AEAD ciphers share the same 12-byte nonce / 16-byte tag shape.
105        CryptoId::ChaCha20Poly1305 | CryptoId::Aes256Gcm => {
106            let end = offset + 28;
107            if entry.len() < end {
108                return Err(crate::Error::Truncated);
109            }
110            let mut nonce = [0u8; 12];
111            let mut tag = [0u8; 16];
112            nonce.copy_from_slice(&entry[offset..offset + 12]);
113            tag.copy_from_slice(&entry[offset + 12..end]);
114            offset = end;
115            (Some(nonce), Some(tag))
116        }
117    };
118
119    Ok(Header {
120        codec,
121        crypto,
122        orig_len,
123        nonce,
124        tag,
125        payload_offset: offset,
126        aad_len: 1 + used,
127    })
128}
129
130#[cfg(all(test, feature = "enc", feature = "dec"))]
131mod tests {
132    use super::*;
133    use alloc::vec::Vec;
134
135    #[test]
136    fn plain_entry_roundtrip() {
137        let mut buf = Vec::new();
138        write_entry(
139            &mut buf,
140            CodecId::Store,
141            CryptoId::None,
142            3,
143            None,
144            &[1, 2, 3],
145        );
146        let h = read_header(&buf).unwrap();
147        assert_eq!(h.codec, CodecId::Store);
148        assert_eq!(h.crypto, CryptoId::None);
149        assert_eq!(h.orig_len, 3);
150        assert!(h.nonce.is_none());
151        // Tag byte plus a one-byte varint, and nothing between that and the
152        // payload for a plain entry.
153        assert_eq!(h.aad_len, 2);
154        assert_eq!(h.payload_offset, h.aad_len);
155        assert_eq!(&buf[h.payload_offset..], &[1, 2, 3]);
156    }
157
158    #[test]
159    fn encrypted_entry_roundtrip() {
160        let nonce = [9u8; 12];
161        let tag = [7u8; 16];
162        let mut buf = Vec::new();
163        write_entry(
164            &mut buf,
165            CodecId::Deflate,
166            CryptoId::ChaCha20Poly1305,
167            100,
168            Some((nonce, tag)),
169            &[0xAA, 0xBB],
170        );
171        let h = read_header(&buf).unwrap();
172        assert_eq!(h.codec, CodecId::Deflate);
173        assert_eq!(h.crypto, CryptoId::ChaCha20Poly1305);
174        assert_eq!(h.orig_len, 100);
175        assert_eq!(h.nonce, Some(nonce));
176        assert_eq!(h.tag, Some(tag));
177        // The associated data stops before the nonce and tag: they are
178        // what the cipher writes and checks, not what it is told.
179        assert_eq!(h.aad_len, 2);
180        assert_eq!(h.payload_offset, h.aad_len + 12 + 16);
181        let mut header = Vec::new();
182        write_header(
183            &mut header,
184            CodecId::Deflate,
185            CryptoId::ChaCha20Poly1305,
186            100,
187        );
188        assert_eq!(header, &buf[..h.aad_len]);
189        assert_eq!(&buf[h.payload_offset..], &[0xAA, 0xBB]);
190    }
191
192    #[test]
193    fn aes_encrypted_entry_roundtrip() {
194        let nonce = [3u8; 12];
195        let tag = [4u8; 16];
196        let mut buf = Vec::new();
197        write_entry(
198            &mut buf,
199            CodecId::Store,
200            CryptoId::Aes256Gcm,
201            5,
202            Some((nonce, tag)),
203            &[0xCC, 0xDD],
204        );
205        let h = read_header(&buf).unwrap();
206        assert_eq!(h.crypto, CryptoId::Aes256Gcm);
207        assert_eq!(h.nonce, Some(nonce));
208        assert_eq!(h.tag, Some(tag));
209        assert_eq!(&buf[h.payload_offset..], &[0xCC, 0xDD]);
210    }
211
212    #[test]
213    fn truncated_header_errors() {
214        assert!(read_header(&[]).is_err());
215    }
216}