Skip to main content

gent_daemon/
file_objects.rs

1//! Trusted endpoint storage for immutable encrypted files. Agent bindings and
2//! permission checks live in store::files; the dispatcher moves only ciphertext.
3//!
4//! The caller must authenticate agents and check current message/file permissions
5//! before every operation. Grants here live in the protected endpoint database;
6//! only ciphertext goes to object storage. Mutations share the caller's immediate
7//! transaction so a message and its files commit or roll back together.
8use anyhow::{Context, Result, ensure};
9use gent_crypto::files::{FileGrant, SealedFile};
10use rusqlite::{Connection, OptionalExtension, Transaction, TransactionBehavior, params};
11use sha2::{Digest, Sha256};
12use zeroize::Zeroizing;
13
14pub const MAX_OBJECTS: u64 = 128;
15pub const MAX_RESERVED_BYTES: u64 = 256 * 1024 * 1024;
16pub const INCOMPLETE_TTL_SECONDS: u64 = 60 * 60;
17pub const MAX_RETENTION_SECONDS: u64 = 7 * 24 * 60 * 60;
18
19/// Initialize within the same protected database used for endpoint state.
20pub fn initialize(db: &mut Connection) -> Result<()> {
21    ensure!(
22        db.pragma_query_value(None, "foreign_keys", |r| r.get::<_, bool>(0))?,
23        "file storage requires foreign keys"
24    );
25    let tx = db.transaction_with_behavior(TransactionBehavior::Immediate)?;
26    tx.execute_batch(
27        "CREATE TABLE IF NOT EXISTS file_object_schema (
28            id INTEGER PRIMARY KEY CHECK(id=1), version INTEGER NOT NULL);
29         INSERT OR IGNORE INTO file_object_schema VALUES(1,1);",
30    )?;
31    check_version(&tx)?;
32    tx.execute_batch(
33        "CREATE TABLE IF NOT EXISTS file_objects (
34            id TEXT PRIMARY KEY,
35            grant BLOB NOT NULL,
36            reserved_bytes INTEGER NOT NULL CHECK(reserved_bytes>=16),
37            expires_at INTEGER NOT NULL,
38            incomplete_until INTEGER NOT NULL,
39            complete INTEGER NOT NULL DEFAULT 0 CHECK(complete IN (0,1)));
40         CREATE TABLE IF NOT EXISTS file_chunks (
41            object_id TEXT NOT NULL REFERENCES file_objects(id) ON DELETE CASCADE,
42            position INTEGER NOT NULL CHECK(position>=0 AND position<128),
43            ciphertext BLOB NOT NULL CHECK(length(ciphertext)>=16 AND length(ciphertext)<=262160),
44            uploaded INTEGER NOT NULL DEFAULT 0 CHECK(uploaded IN (0,1)),
45            PRIMARY KEY(object_id,position));",
46    )?;
47    tx.commit()?;
48    Ok(())
49}
50
51fn check_version(db: &Connection) -> Result<()> {
52    let version: u64 = db.query_row(
53        "SELECT version FROM file_object_schema WHERE id=1",
54        [],
55        |r| r.get(0),
56    )?;
57    ensure!(version == 1, "unsupported file storage version");
58    Ok(())
59}
60
61pub struct Objects<'a> {
62    db: &'a Connection,
63    now: u64,
64}
65
66#[derive(Clone, Debug, PartialEq, Eq)]
67pub struct Status {
68    pub complete: bool,
69    pub chunks_present: u32,
70    pub chunks_uploaded: u32,
71    pub expires_at: u64,
72    pub incomplete_until: u64,
73}
74
75impl<'a> Objects<'a> {
76    /// Use an immediate transaction and propagate errors before committing.
77    /// This constructor deliberately cannot take an autocommit Connection.
78    pub fn new(tx: &'a Transaction<'_>, now: u64) -> Result<Self> {
79        Self::in_transaction(tx, now)
80    }
81
82    pub(crate) fn in_transaction(tx: &'a Connection, now: u64) -> Result<Self> {
83        ensure!(!tx.is_autocommit(), "file storage requires a transaction");
84        ensure!(
85            now <= i64::MAX as u64 - MAX_RETENTION_SECONDS,
86            "invalid file storage clock"
87        );
88        check_version(tx)?;
89        ensure!(
90            tx.pragma_query_value(None, "foreign_keys", |r| r.get::<_, bool>(0))?,
91            "file storage requires foreign keys"
92        );
93        Ok(Self { db: tx, now })
94    }
95
96    /// Reserve the entire object before accepting any chunks. Exact retries do
97    /// not consume more quota, replace a grant, or extend its local lifetime.
98    pub fn expect(&self, grant: &FileGrant, expires_at: u64) -> Result<()> {
99        ensure!(
100            expires_at > self.now && expires_at <= self.now + MAX_RETENTION_SECONDS,
101            "invalid file retention deadline"
102        );
103        let id = &grant.descriptor().id;
104        let encoded = grant.encode_private()?;
105        let previous: Option<(Vec<u8>, u64)> = self
106            .db
107            .query_row(
108                "SELECT grant,expires_at FROM file_objects WHERE id=?1",
109                [id],
110                |r| Ok((r.get(0)?, r.get(1)?)),
111            )
112            .optional()?;
113        if let Some((previous, expiry)) = previous {
114            let previous = Zeroizing::new(previous);
115            ensure!(
116                *previous == *encoded && expiry == expires_at,
117                "conflicting file object"
118            );
119            self.status(id)?;
120            return Ok(());
121        }
122        self.reap()?;
123        let (count, reserved): (u64, u64) = self.db.query_row(
124            "SELECT COUNT(*),COALESCE(SUM(reserved_bytes),0) FROM file_objects",
125            [],
126            |r| Ok((r.get(0)?, r.get(1)?)),
127        )?;
128        ensure!(
129            count < MAX_OBJECTS && reserved + grant.ciphertext_bytes() <= MAX_RESERVED_BYTES,
130            "file storage quota exhausted"
131        );
132        self.db.execute(
133            "INSERT INTO file_objects(id,grant,reserved_bytes,expires_at,incomplete_until)
134             VALUES(?1,?2,?3,?4,?5)",
135            params![
136                id,
137                encoded.as_slice(),
138                grant.ciphertext_bytes(),
139                expires_at,
140                expires_at.min(self.now + INCOMPLETE_TTL_SECONDS)
141            ],
142        )?;
143        Ok(())
144    }
145
146    /// Persist the complete encrypted representation in the message transaction.
147    pub fn stage(&self, sealed: &SealedFile, expires_at: u64) -> Result<()> {
148        self.expect(sealed.grant(), expires_at)?;
149        let id = &sealed.grant().descriptor().id;
150        // SealedFile can only be constructed by the crypto module. It is immutable
151        // and already binds its complete plaintext digest and every chunk.
152        for (index, bytes) in sealed.chunks().iter().enumerate() {
153            self.insert_chunk(id, index as u32, bytes)?;
154        }
155        self.db
156            .execute("UPDATE file_objects SET complete=1 WHERE id=?1", [id])?;
157        Ok(())
158    }
159
160    fn insert_chunk(&self, id: &str, index: u32, bytes: &[u8]) -> Result<()> {
161        let previous: Option<Vec<u8>> = self
162            .db
163            .query_row(
164                "SELECT ciphertext FROM file_chunks WHERE object_id=?1 AND position=?2",
165                params![id, index],
166                |r| r.get(0),
167            )
168            .optional()?;
169        if let Some(previous) = previous {
170            ensure!(previous == bytes, "conflicting file chunk");
171        } else {
172            self.db.execute(
173                "INSERT INTO file_chunks(object_id,position,ciphertext) VALUES(?1,?2,?3)",
174                params![id, index, bytes],
175            )?;
176        }
177        Ok(())
178    }
179
180    pub fn status(&self, id: &str) -> Result<Status> {
181        let status = self
182            .db
183            .query_row(
184                "SELECT complete,expires_at,incomplete_until,
185                    (SELECT COUNT(*) FROM file_chunks WHERE object_id=?1),
186                    (SELECT COALESCE(SUM(uploaded),0) FROM file_chunks WHERE object_id=?1)
187                 FROM file_objects WHERE id=?1",
188                [id],
189                |r| {
190                    Ok(Status {
191                        complete: r.get(0)?,
192                        expires_at: r.get(1)?,
193                        incomplete_until: r.get(2)?,
194                        chunks_present: r.get(3)?,
195                        chunks_uploaded: r.get(4)?,
196                    })
197                },
198            )
199            .optional()?
200            .context("file object unavailable")?;
201        ensure!(
202            status.expires_at > self.now && (status.complete || status.incomplete_until > self.now),
203            "file object unavailable"
204        );
205        Ok(status)
206    }
207
208    /// Private grant for an already authorized message or local operation.
209    pub fn grant(&self, id: &str) -> Result<FileGrant> {
210        self.status(id)?;
211        let encoded = Zeroizing::new(self.db.query_row(
212            "SELECT grant FROM file_objects WHERE id=?1",
213            [id],
214            |r| r.get::<_, Vec<u8>>(0),
215        )?);
216        let grant = FileGrant::decode_private(&encoded)?;
217        ensure!(grant.descriptor().id == id, "file object identity mismatch");
218        Ok(grant)
219    }
220
221    pub fn missing_chunks(&self, id: &str) -> Result<Vec<u32>> {
222        let grant = self.grant(id)?;
223        let mut query = self.db.prepare(
224            "SELECT EXISTS(SELECT 1 FROM file_chunks WHERE object_id=?1 AND position=?2)",
225        )?;
226        let mut missing = Vec::new();
227        for index in 0..grant.chunk_count() {
228            if !query.query_row(params![id, index], |r| r.get::<_, bool>(0))? {
229                missing.push(index);
230            }
231        }
232        Ok(missing)
233    }
234
235    /// Verify before durable storage. Out-of-order arrivals and identical retries
236    /// are allowed; completion requires a separate whole-file integrity check.
237    pub fn accept_chunk(&self, id: &str, index: u32, bytes: &[u8]) -> Result<()> {
238        self.grant(id)?.decrypt_chunk(index, bytes)?;
239        self.insert_chunk(id, index, bytes)
240    }
241
242    fn open(&self, id: &str) -> Result<Zeroizing<Vec<u8>>> {
243        let grant = self.grant(id)?;
244        let mut query = self.db.prepare(
245            "SELECT position,ciphertext FROM file_chunks WHERE object_id=?1 ORDER BY position",
246        )?;
247        let chunks = query
248            .query_map([id], |r| Ok((r.get::<_, u32>(0)?, r.get::<_, Vec<u8>>(1)?)))?
249            .collect::<rusqlite::Result<Vec<_>>>()?;
250        ensure!(
251            chunks
252                .iter()
253                .enumerate()
254                .all(|(index, (saved, _))| index as u32 == *saved),
255            "incomplete file object"
256        );
257        grant.open(
258            &chunks
259                .into_iter()
260                .map(|(_, bytes)| bytes)
261                .collect::<Vec<_>>(),
262        )
263    }
264
265    pub fn finish(&self, id: &str) -> Result<()> {
266        self.open(id)?;
267        self.db
268            .execute("UPDATE file_objects SET complete=1 WHERE id=?1", [id])?;
269        Ok(())
270    }
271
272    fn ready(&self, id: &str) -> Result<FileGrant> {
273        let status = self.status(id)?;
274        let grant = self.grant(id)?;
275        let present: u32 = self.db.query_row(
276            "SELECT COUNT(*) FROM file_chunks WHERE object_id=?1 AND position<?2",
277            params![id, grant.chunk_count()],
278            |r| r.get(0),
279        )?;
280        ensure!(
281            status.complete
282                && status.chunks_present == grant.chunk_count()
283                && present == grant.chunk_count(),
284            "file object incomplete"
285        );
286        Ok(grant)
287    }
288
289    pub fn read(&self, id: &str) -> Result<Zeroizing<Vec<u8>>> {
290        self.ready(id)?;
291        self.open(id)
292    }
293
294    /// Authenticate one plaintext chunk of a completed object. Completion already
295    /// checked the whole-file digest; reassemblers should check it again. This
296    /// reads only the selected ciphertext, not the entire file on every call.
297    pub fn read_chunk(&self, id: &str, index: u32) -> Result<Zeroizing<Vec<u8>>> {
298        let grant = self.ready(id)?;
299        grant.ciphertext_len(index)?;
300        let bytes: Vec<u8> = self.db.query_row(
301            "SELECT ciphertext FROM file_chunks WHERE object_id=?1 AND position=?2",
302            params![id, index],
303            |r| r.get(0),
304        )?;
305        grant.decrypt_chunk(index, &bytes)
306    }
307
308    /// Reconstruct the public storage manifest after restart from saved immutable
309    /// chunks and the original deadline. This never exports a private grant.
310    pub fn transport_manifest(&self, id: &str) -> Result<gent_protocol::file_objects::Manifest> {
311        use gent_protocol::file_objects::{Chunk, Manifest};
312        let grant = self.ready(id)?;
313        let mut chunks = Vec::with_capacity(grant.chunk_count() as usize);
314        for index in 0..grant.chunk_count() {
315            let bytes = self.upload_chunk(id, index)?;
316            chunks.push(Chunk {
317                bytes: bytes.len() as u32,
318                sha256: format!("{:x}", Sha256::digest(bytes)),
319            });
320        }
321        let manifest = Manifest {
322            version: 1,
323            chunks,
324            expires_at: self.status(id)?.expires_at,
325        };
326        manifest.validate().map_err(anyhow::Error::msg)?;
327        Ok(manifest)
328    }
329
330    /// Uploads expose only fully persisted objects, never partial local imports.
331    pub fn upload_chunk(&self, id: &str, index: u32) -> Result<Vec<u8>> {
332        let grant = self.ready(id)?;
333        let bytes: Vec<u8> = self
334            .db
335            .query_row(
336                "SELECT ciphertext FROM file_chunks WHERE object_id=?1 AND position=?2",
337                params![id, index],
338                |r| r.get(0),
339            )
340            .optional()?
341            .context("file chunk unavailable")?;
342        grant.decrypt_chunk(index, &bytes)?;
343        Ok(bytes)
344    }
345
346    pub fn pending_uploads(&self, id: &str) -> Result<Vec<u32>> {
347        self.ready(id)?;
348        let mut query = self.db.prepare(
349            "SELECT position FROM file_chunks WHERE object_id=?1 AND uploaded=0 ORDER BY position",
350        )?;
351        Ok(query
352            .query_map([id], |r| r.get(0))?
353            .collect::<rusqlite::Result<_>>()?)
354    }
355
356    /// Records service storage only; this never means chat delivery or completion.
357    pub fn acknowledge_upload(&self, id: &str, index: u32) -> Result<()> {
358        self.ready(id)?.ciphertext_len(index)?;
359        ensure!(
360            self.db.execute(
361                "UPDATE file_chunks SET uploaded=1 WHERE object_id=?1 AND position=?2",
362                params![id, index],
363            )? == 1,
364            "file chunk unavailable"
365        );
366        Ok(())
367    }
368
369    /// Recover after relay storage loss using the same persisted ciphertext.
370    pub fn retry_upload(&self, id: &str) -> Result<()> {
371        self.ready(id)?;
372        self.db
373            .execute("UPDATE file_chunks SET uploaded=0 WHERE object_id=?1", [id])?;
374        Ok(())
375    }
376
377    pub fn delete(&self, id: &str) -> Result<bool> {
378        Ok(self
379            .db
380            .execute("DELETE FROM file_objects WHERE id=?1", [id])?
381            != 0)
382    }
383
384    /// Releases logical quota, including grants and abandoned partial downloads.
385    /// SQLite/WAL/backups may retain old pages; this is not forensic erasure.
386    pub fn reap(&self) -> Result<usize> {
387        Ok(self.db.execute(
388            "DELETE FROM file_objects WHERE expires_at<=?1 OR (complete=0 AND incomplete_until<=?1)",
389            [self.now],
390        )?)
391    }
392}