Skip to main content

gent_crypto/
files.rs

1//! Immutable file objects for storage outside message envelopes.
2//!
3//! Only ciphertext, an opaque object ID, and a chunk index belong at the relay.
4//! Grants contain private metadata and a key: carry them inside authenticated
5//! encrypted messages. Possession of a grant is not an agent authorization check.
6use anyhow::{Result, ensure};
7use chacha20poly1305::{
8    ChaCha20Poly1305, KeyInit,
9    aead::{Aead, Payload},
10};
11use gent_protocol::FileDescriptor;
12use serde::{Deserialize, Serialize};
13use sha2::{Digest as _, Sha256};
14use uuid::Uuid;
15use zeroize::{Zeroize, Zeroizing};
16
17pub use gent_protocol::file_objects::{CHUNK_BYTES, MAX_CHUNKS, MAX_FILE_BYTES, TAG_BYTES};
18pub const MAX_GRANT_BYTES: usize = 2048;
19
20/// No Debug, Serialize, or public key accessor: exporting a grant must be explicit.
21pub struct FileGrant {
22    manifest: FileDescriptor,
23    key: Zeroizing<[u8; 32]>,
24}
25
26#[derive(Serialize, Deserialize)]
27#[serde(deny_unknown_fields)]
28struct WireGrant {
29    version: u8,
30    manifest: FileDescriptor,
31    key: [u8; 32],
32}
33
34impl Drop for WireGrant {
35    fn drop(&mut self) {
36        self.key.zeroize();
37    }
38}
39
40/// An object is sealed once with a fresh key. There is deliberately no API for
41/// encrypting caller-selected bytes under an existing grant and chunk nonce.
42pub struct SealedFile {
43    grant: FileGrant,
44    chunks: Vec<Vec<u8>>,
45}
46
47impl SealedFile {
48    pub fn grant(&self) -> &FileGrant {
49        &self.grant
50    }
51
52    pub fn chunks(&self) -> &[Vec<u8>] {
53        &self.chunks
54    }
55
56    /// The only metadata needed by object storage. Its hashes cover ciphertext.
57    pub fn transport_manifest(
58        &self,
59        expires_at: u64,
60    ) -> Result<gent_protocol::file_objects::Manifest> {
61        let manifest = gent_protocol::file_objects::Manifest {
62            version: 1,
63            chunks: self
64                .chunks
65                .iter()
66                .map(|bytes| gent_protocol::file_objects::Chunk {
67                    bytes: bytes.len() as u32,
68                    sha256: format!("{:x}", Sha256::digest(bytes)),
69                })
70                .collect(),
71            expires_at,
72        };
73        manifest.validate().map_err(anyhow::Error::msg)?;
74        Ok(manifest)
75    }
76}
77
78fn validate(manifest: &FileDescriptor) -> Result<()> {
79    let id = Uuid::parse_str(&manifest.id)?;
80    ensure!(
81        id.get_version_num() == 4
82            && id.get_variant() == uuid::Variant::RFC4122
83            && id.to_string() == manifest.id,
84        "invalid file object ID"
85    );
86    validate_metadata(&manifest.name, &manifest.media_type)?;
87    ensure!(
88        manifest.byte_length <= MAX_FILE_BYTES as u64,
89        "file exceeds 32 MiB"
90    );
91    ensure!(
92        manifest.sha256.len() == 64
93            && manifest
94                .sha256
95                .bytes()
96                .all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b)),
97        "invalid file digest"
98    );
99    Ok(())
100}
101
102pub fn validate_metadata(name: &str, media_type: &str) -> Result<()> {
103    ensure!(
104        (1..=128).contains(&name.len())
105            && !name.trim().is_empty()
106            && !name.chars().any(char::is_control)
107            && !name.contains(['/', '\\'])
108            && name != "."
109            && name != "..",
110        "invalid file basename"
111    );
112    // A bare media type, without parameters, paths, or header delimiters.
113    let token = |s: &str| {
114        !s.is_empty()
115            && s.bytes().all(|b| {
116                b.is_ascii_alphanumeric()
117                    || matches!(
118                        b,
119                        b'!' | b'#' | b'$' | b'&' | b'^' | b'_' | b'.' | b'+' | b'-'
120                    )
121            })
122    };
123    ensure!(
124        media_type.len() <= 128
125            && media_type
126                .split_once('/')
127                .is_some_and(|(kind, subtype)| token(kind) && token(subtype)),
128        "invalid file media type"
129    );
130    Ok(())
131}
132
133impl FileGrant {
134    pub fn descriptor(&self) -> &FileDescriptor {
135        &self.manifest
136    }
137
138    pub fn chunk_count(&self) -> u32 {
139        (self.manifest.byte_length as usize)
140            .div_ceil(CHUNK_BYTES)
141            .max(1) as u32
142    }
143
144    pub fn ciphertext_len(&self, index: u32) -> Result<usize> {
145        ensure!(index < self.chunk_count(), "invalid file chunk index");
146        Ok(
147            (self.manifest.byte_length as usize - index as usize * CHUNK_BYTES).min(CHUNK_BYTES)
148                + TAG_BYTES,
149        )
150    }
151
152    pub fn ciphertext_bytes(&self) -> u64 {
153        self.manifest.byte_length + u64::from(self.chunk_count()) * TAG_BYTES as u64
154    }
155
156    /// Secret output: only trusted local storage or an encrypted wire record.
157    pub fn encode_private(&self) -> Result<Zeroizing<Vec<u8>>> {
158        let wire = WireGrant {
159            version: 1,
160            manifest: self.manifest.clone(),
161            key: *self.key,
162        };
163        let bytes = Zeroizing::new(serde_json::to_vec(&wire)?);
164        ensure!(bytes.len() <= MAX_GRANT_BYTES, "file grant too large");
165        Ok(bytes)
166    }
167
168    /// Call only after authenticating the enclosing message and its recipient.
169    pub fn decode_private(bytes: &[u8]) -> Result<Self> {
170        ensure!(bytes.len() <= MAX_GRANT_BYTES, "file grant too large");
171        // Suppress serde's value-bearing diagnostics for secret input.
172        let wire: WireGrant =
173            serde_json::from_slice(bytes).map_err(|_| anyhow::anyhow!("invalid file grant"))?;
174        ensure!(wire.version == 1, "unsupported file grant version");
175        validate(&wire.manifest)?;
176        Ok(Self {
177            manifest: wire.manifest.clone(),
178            key: Zeroizing::new(wire.key),
179        })
180    }
181
182    fn aad(&self, index: u32) -> Vec<u8> {
183        // Explicit binary encoding; JSON field order cannot change authentication.
184        let mut aad = b"gent/file-chunk/v1\0".to_vec();
185        for field in [
186            self.manifest.id.as_bytes(),
187            self.manifest.name.as_bytes(),
188            self.manifest.media_type.as_bytes(),
189            self.manifest.sha256.as_bytes(),
190        ] {
191            aad.extend_from_slice(&(field.len() as u16).to_be_bytes());
192            aad.extend_from_slice(field);
193        }
194        aad.extend_from_slice(&self.manifest.byte_length.to_be_bytes());
195        aad.extend_from_slice(&self.chunk_count().to_be_bytes());
196        aad.extend_from_slice(&index.to_be_bytes());
197        aad
198    }
199
200    /// Authenticating one chunk supports resumable downloads. Call open() before
201    /// exposing a complete file; it also checks the whole-file SHA-256 digest.
202    pub fn decrypt_chunk(&self, index: u32, ciphertext: &[u8]) -> Result<Zeroizing<Vec<u8>>> {
203        ensure!(
204            ciphertext.len() == self.ciphertext_len(index)?,
205            "invalid file chunk length"
206        );
207        let cipher = ChaCha20Poly1305::new((&*self.key).into());
208        let plaintext = cipher
209            .decrypt(
210                (&nonce(index)).into(),
211                Payload {
212                    msg: ciphertext,
213                    aad: &self.aad(index),
214                },
215            )
216            .map_err(|_| anyhow::anyhow!("file chunk authentication failed"))?;
217        Ok(Zeroizing::new(plaintext))
218    }
219
220    pub fn open(&self, chunks: &[Vec<u8>]) -> Result<Zeroizing<Vec<u8>>> {
221        ensure!(
222            chunks.len() == self.chunk_count() as usize,
223            "incomplete file object"
224        );
225        let mut plaintext = Zeroizing::new(Vec::with_capacity(self.manifest.byte_length as usize));
226        for (index, chunk) in chunks.iter().enumerate() {
227            plaintext.extend_from_slice(&self.decrypt_chunk(index as u32, chunk)?);
228        }
229        ensure!(
230            format!("{:x}", Sha256::digest(&plaintext)) == self.manifest.sha256,
231            "file integrity check failed"
232        );
233        Ok(plaintext)
234    }
235}
236
237fn nonce(index: u32) -> [u8; 12] {
238    let mut nonce = [0; 12];
239    nonce[8..].copy_from_slice(&index.to_be_bytes());
240    nonce
241}
242
243/// New calls, including forwarding the same bytes, use independent object IDs
244/// and keys. Retries must reuse the saved SealedFile instead of sealing again.
245pub fn seal(name: &str, media_type: &str, plaintext: &[u8]) -> Result<SealedFile> {
246    ensure!(plaintext.len() <= MAX_FILE_BYTES, "file exceeds 32 MiB");
247    let manifest = FileDescriptor {
248        id: Uuid::new_v4().to_string(),
249        name: name.into(),
250        media_type: media_type.into(),
251        byte_length: plaintext.len() as u64,
252        sha256: format!("{:x}", Sha256::digest(plaintext)),
253    };
254    validate(&manifest)?;
255    let mut key = Zeroizing::new([0; 32]);
256    getrandom::fill(&mut *key)?;
257    let grant = FileGrant { manifest, key };
258    let cipher = ChaCha20Poly1305::new((&*grant.key).into());
259    let mut chunks = Vec::with_capacity(grant.chunk_count() as usize);
260    for index in 0..grant.chunk_count() {
261        let start = index as usize * CHUNK_BYTES;
262        let end = (start + CHUNK_BYTES).min(plaintext.len());
263        let ciphertext = cipher
264            .encrypt(
265                (&nonce(index)).into(),
266                Payload {
267                    msg: &plaintext[start..end],
268                    aad: &grant.aad(index),
269                },
270            )
271            .map_err(|_| anyhow::anyhow!("file encryption failed"))?;
272        chunks.push(ciphertext);
273    }
274    Ok(SealedFile { grant, chunks })
275}
276
277#[cfg(test)]
278mod tests {
279    use super::*;
280
281    #[test]
282    fn authenticated_chunks_still_require_the_whole_file_digest() {
283        let sealed = seal("test.bin", "application/octet-stream", b"correct").unwrap();
284        let grant = sealed.grant();
285        // A faulty or malicious authenticated sender can encrypt bytes that do
286        // not match its advertised hash. Per-chunk AEAD alone cannot catch that.
287        let ciphertext = ChaCha20Poly1305::new((&*grant.key).into())
288            .encrypt(
289                (&nonce(0)).into(),
290                Payload {
291                    msg: b"changed",
292                    aad: &grant.aad(0),
293                },
294            )
295            .unwrap();
296        assert_eq!(&*grant.decrypt_chunk(0, &ciphertext).unwrap(), b"changed");
297        let error = grant.open(&[ciphertext]).unwrap_err();
298        assert_eq!(error.to_string(), "file integrity check failed");
299    }
300}