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}
36
37/// Appends one complete entry -- header followed by `payload` -- to `out`.
38///
39/// `orig_len` is the length of the file before compression, and `nonce_tag`
40/// carries the AEAD nonce and tag when the payload was sealed. Pass `None`
41/// for a plaintext entry; `crypto` and `nonce_tag` have to agree, since
42/// [`read_header`] decides whether to expect the 28 nonce-and-tag bytes from
43/// `crypto` alone.
44#[cfg(feature = "enc")]
45pub fn write_entry(
46    out: &mut Vec<u8>,
47    codec: CodecId,
48    crypto: CryptoId,
49    orig_len: u64,
50    nonce_tag: Option<([u8; 12], [u8; 16])>,
51    payload: &[u8],
52) {
53    out.push(codec.as_u8() | (crypto.as_u8() << 4));
54    crate::write_varint(out, orig_len);
55    if let Some((nonce, tag)) = nonce_tag {
56        out.extend_from_slice(&nonce);
57        out.extend_from_slice(&tag);
58    }
59    out.extend_from_slice(payload);
60}
61
62/// Parses the header at the front of `entry`.
63///
64/// Only the header is examined; the payload is left to the caller, which
65/// finds it at [`Header::payload_offset`]. Nothing is copied out of the
66/// payload and no allocation happens here, so this is cheap enough to call
67/// just to read [`Header::orig_len`].
68///
69/// # Errors
70///
71/// Returns [`Error::Truncated`](crate::Error::Truncated) if `entry` is
72/// shorter than the header it declares, [`Error::Corrupt`](crate::Error::Corrupt)
73/// if the length varint is malformed, and
74/// [`Error::UnknownCodec`](crate::Error::UnknownCodec) or
75/// [`Error::UnknownCrypto`](crate::Error::UnknownCrypto) if the tag byte
76/// names an unassigned id.
77#[cfg(feature = "dec")]
78pub fn read_header(entry: &[u8]) -> Result<Header> {
79    let tag_byte = *entry.first().ok_or(crate::Error::Truncated)?;
80    let codec = CodecId::from_u8(tag_byte & 0x0f)?;
81    let crypto = CryptoId::from_u8(tag_byte >> 4)?;
82    let (orig_len, used) = crate::read_varint(&entry[1..])?;
83    let mut offset = 1 + used;
84
85    let (nonce, tag) = match crypto {
86        CryptoId::None => (None, None),
87        // Both AEAD ciphers share the same 12-byte nonce / 16-byte tag shape.
88        CryptoId::ChaCha20Poly1305 | CryptoId::Aes256Gcm => {
89            let end = offset + 28;
90            if entry.len() < end {
91                return Err(crate::Error::Truncated);
92            }
93            let mut nonce = [0u8; 12];
94            let mut tag = [0u8; 16];
95            nonce.copy_from_slice(&entry[offset..offset + 12]);
96            tag.copy_from_slice(&entry[offset + 12..end]);
97            offset = end;
98            (Some(nonce), Some(tag))
99        }
100    };
101
102    Ok(Header {
103        codec,
104        crypto,
105        orig_len,
106        nonce,
107        tag,
108        payload_offset: offset,
109    })
110}
111
112#[cfg(all(test, feature = "enc", feature = "dec"))]
113mod tests {
114    use super::*;
115    use alloc::vec::Vec;
116
117    #[test]
118    fn plain_entry_roundtrip() {
119        let mut buf = Vec::new();
120        write_entry(
121            &mut buf,
122            CodecId::Store,
123            CryptoId::None,
124            3,
125            None,
126            &[1, 2, 3],
127        );
128        let h = read_header(&buf).unwrap();
129        assert_eq!(h.codec, CodecId::Store);
130        assert_eq!(h.crypto, CryptoId::None);
131        assert_eq!(h.orig_len, 3);
132        assert!(h.nonce.is_none());
133        assert_eq!(&buf[h.payload_offset..], &[1, 2, 3]);
134    }
135
136    #[test]
137    fn encrypted_entry_roundtrip() {
138        let nonce = [9u8; 12];
139        let tag = [7u8; 16];
140        let mut buf = Vec::new();
141        write_entry(
142            &mut buf,
143            CodecId::Deflate,
144            CryptoId::ChaCha20Poly1305,
145            100,
146            Some((nonce, tag)),
147            &[0xAA, 0xBB],
148        );
149        let h = read_header(&buf).unwrap();
150        assert_eq!(h.codec, CodecId::Deflate);
151        assert_eq!(h.crypto, CryptoId::ChaCha20Poly1305);
152        assert_eq!(h.orig_len, 100);
153        assert_eq!(h.nonce, Some(nonce));
154        assert_eq!(h.tag, Some(tag));
155        assert_eq!(&buf[h.payload_offset..], &[0xAA, 0xBB]);
156    }
157
158    #[test]
159    fn aes_encrypted_entry_roundtrip() {
160        let nonce = [3u8; 12];
161        let tag = [4u8; 16];
162        let mut buf = Vec::new();
163        write_entry(
164            &mut buf,
165            CodecId::Store,
166            CryptoId::Aes256Gcm,
167            5,
168            Some((nonce, tag)),
169            &[0xCC, 0xDD],
170        );
171        let h = read_header(&buf).unwrap();
172        assert_eq!(h.crypto, CryptoId::Aes256Gcm);
173        assert_eq!(h.nonce, Some(nonce));
174        assert_eq!(h.tag, Some(tag));
175        assert_eq!(&buf[h.payload_offset..], &[0xCC, 0xDD]);
176    }
177
178    #[test]
179    fn truncated_header_errors() {
180        assert!(read_header(&[]).is_err());
181    }
182}