Cotton code
241 lines · 12.0 KB · RustRaw
//! A person's own files, sealed on this device before they leave it and//! opened here when they come back (R6).//!//! The drain's transport seals a picture, a video, a book, a song or a film//! as it reads it off the store (`SealingReader`: f1 parts made as they are//! sent, so an upload in parts resumes at any part with no sealed copy on//! disk); the object stores bytes it cannot read, typed//! [`SEALED_FILE_TYPE`]. The file's key is made here from the person's data//! key and the object key alone (`person_file_key`), so the row needs no//! column for it and every device holding the DK opens it.//!//! **Never clear.** With no data key on this device yet, a file waits (a//! transient refusal the drain backs off on), never goes up open. A file that//! comes down not sealed opens only when its bytes are the ones its key's//! sha256 names (a file stored before R6): no other clear bytes are ever//! taken in place of a sealed file.use std::io::{Read, Seek, SeekFrom, Write};use std::path::Path;use std::sync::Arc;use cotton_core::seal::arrival_file;use cotton_core::seal::file::{self, FileKey, OpeningReader};use sha2::{Digest, Sha256};use crate::seal::DataKeyStore;use crate::transport::ServerRefusal;/// The type a sealed file is stored and served as (the Worker's `SEALED_FILE_TYPE`).pub const SEALED_FILE_TYPE: &str = "application/vnd.cotton.f1";/// The kinds of a person's files sealed here: each `<database id>/<kind>/…`.////// `messages`: a chat picture kept in the person's own media (`<db>/messages/<thread>/<sha>.<ext>`, chat_files::keep),/// sealed since 22 Nov 2026 (owner's decision) under the message table's own files root, which a window over/// messages hands the Worker (`seal::keys::table_file_root`), so an assistant reads it in a window and nowhere else./// `mail`: what a message brought on the person's own domain (`<db>/mail/<email>/<index>`, the raw message/// `<db>/mail/in/<arrival>.eml`), sealed at arrival by the Worker to the arrival key (OWN-MAIL.md, 22 Nov 2026)./// `people`: a person's picture (`<db>/people/<person>/<sha>.<ext>`, `capture.avatar`) and the one WhatsApp gave/// (`<db>/people/<person>/whatsapp/<sha>.<ext>`, the Mac's), sealed since AVATAR SEAL (MEDIA SEAL FINDINGS (1),/// 27 Nov 2026) under the person table's own files root, so a window over people opens a face and nothing else does./// One the object still holds plain opens here while its bytes are the ones its name's sha256 names.pub const SEALED_KINDS: &[&str] = &["photos", "videos", "books", "music", "films", "meetings", "messages", "mail", "people"];/// The tables whose rows name a person's files: an app keeping any of them needs the data key (`seal.status`).pub const FILE_TABLES: &[&str] = &["photo", "video", "book", "song", "film", "film_episode", "meeting", "meetings_meeting"];/// One database's files and the data key that opens them.pub struct PersonFiles {    database: String,    keys: Arc<dyn DataKeyStore>,}impl std::fmt::Debug for PersonFiles {    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {        f.debug_struct("PersonFiles").field("database", &self.database).finish_non_exhaustive()    }}impl PersonFiles {    pub fn new(database: impl Into<String>, keys: Arc<dyn DataKeyStore>) -> PersonFiles {        PersonFiles { database: database.into(), keys }    }    /// Whether `key` is one of this database's files this lane seals.    pub fn seals(&self, key: &str) -> bool {        is_person_file(&self.database, key)    }    /// The key that seals and opens `key`; a transient refusal while this device holds no data key.    pub fn file_key(&self, key: &str) -> Result<FileKey, ServerRefusal> {        let dk = self            .keys            .data_key(&self.database)            .map_err(ServerRefusal::offline)?            .ok_or_else(|| ServerRefusal::offline(format!("{}: this device holds no data key yet, so the file waits sealed here", crate::seal::SEAL_KEY_MISSING)))?;        let root = file_root_for(&dk, &self.database, key).map_err(|error| ServerRefusal::offline(error.to_string()))?;        Ok(file::person_file_key(&root, key))    }    /// The key that opens the file fetched into `raw` for `key`: a file the    /// object sealed at arrival carries its own, wrapped to the arrival key    /// this device's DK derives (`arrival_file`); any other is the person's    /// own file key. A transient refusal while no data key is held; a wrap    /// that does not open for this file is refused as not opening.    pub fn key_for_download(&self, key: &str, raw: &Path) -> Result<FileKey, ServerRefusal> {        let Some((_, wrap)) = arrival_head(raw).map_err(|error| ServerRefusal::new(error, 422).with_code("seal_does_not_open".to_string()))? else {            return self.file_key(key);        };        let dk = self            .keys            .data_key(&self.database)            .map_err(ServerRefusal::offline)?            .ok_or_else(|| ServerRefusal::offline(format!("{}: this device holds no data key yet, so the file waits sealed here", crate::seal::SEAL_KEY_MISSING)))?;        arrival_file::file_key(&dk, &self.database, key, &wrap).map_err(|error| ServerRefusal::new(error.to_string(), 422).with_code(error.code().to_string()))    }}impl PersonFiles {    /// The file fetched into `raw` for `key`, opened into `dest`. A clear one (held from before its kind was sealed)    /// needs no key: it is taken when its bytes are the ones its name says, so a device that holds no data key yet    /// still reads an old clear face or chat picture (AVATAR SEAL 2 (2), 27 Nov 2026). Only a sealed one asks for    /// the key, and waits (a transient refusal) while none is held.    pub fn open_fetched(&self, key: &str, raw: &Path, dest: &Path) -> Result<(), ServerRefusal> {        let not_opening = |why: String| ServerRefusal::new(why, 422).with_code("seal_does_not_open".to_string());        let sealed = looks_sealed(raw).map_err(|error| {            let _ = std::fs::remove_file(raw);            not_opening(error.to_string())        })?;        if !sealed {            return open_clear(key, raw, dest).map_err(not_opening);        }        let fk = self.key_for_download(key, raw).inspect_err(|_| {            let _ = std::fs::remove_file(raw);        })?;        open_download(&fk, key, raw, dest).map_err(not_opening)    }}/// A clear file fetched into `raw`, moved to `dest` only when its bytes are the ones `key`'s name says; `raw` goes either way.fn open_clear(key: &str, raw: &Path, dest: &Path) -> Result<(), String> {    let checked = (|| {        let wanted = named_sha(key).ok_or_else(|| format!("{key} came down not sealed, and names no digest its bytes could be checked against"))?;        let mut hasher = Sha256::new();        std::io::copy(&mut std::fs::File::open(raw).map_err(|error| error.to_string())?, &mut hasher).map_err(|error| error.to_string())?;        if hex::encode(hasher.finalize()) != wanted.to_ascii_lowercase() {            return Err(format!("{key} came down not sealed and not the bytes its name says"));        }        std::fs::rename(raw, dest).map_err(|error| error.to_string())    })();    let _ = std::fs::remove_file(raw);    checked}/// An arrival file's head read from `path`: where its inner f1 file starts and/// its wrap; `None` for any other file.fn arrival_head(path: &Path) -> Result<Option<(u64, String)>, String> {    let mut head = Vec::with_capacity(64);    std::fs::File::open(path).map_err(|error| error.to_string())?.take(arrival_file::head_len() as u64).read_to_end(&mut head).map_err(|error| error.to_string())?;    match arrival_file::read_head(&head) {        None => Ok(None),        Some(read) => read.map(Some).map_err(|error| error.code().to_string()),    }}/// A reader over `inner` from byte `start` on, as if the file began there: an/// arrival file's inner f1 file, read past its head.struct Past<S> {    inner: S,    start: u64,}impl<S: Read> Read for Past<S> {    fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {        self.inner.read(buf)    }}impl<S: Seek> Seek for Past<S> {    fn seek(&mut self, pos: SeekFrom) -> std::io::Result<u64> {        let at = match pos {            SeekFrom::Start(n) => self.inner.seek(SeekFrom::Start(self.start + n))?,            other => self.inner.seek(other)?,        };        at.checked_sub(self.start).ok_or_else(|| std::io::Error::new(std::io::ErrorKind::InvalidInput, "a seek before the inner file"))    }}/// The root `key`'s file key is made under: its table's files root for a kind a window opens (a kept chat/// picture), else the person's files root, which no window carries.pub fn file_root_for(dk: &cotton_core::seal::keys::DataKey, database: &str, key: &str) -> Result<cotton_core::seal::keys::Key32, cotton_core::seal::SealError> {    let kind = key.strip_prefix(database).and_then(|rest| rest.strip_prefix('/')).and_then(|rest| rest.split('/').next()).unwrap_or_default();    match cotton_core::seal::keys::table_of_file_kind(kind) {        Some(table) => cotton_core::seal::keys::table_file_root(dk, database, table),        None => cotton_core::seal::keys::file_root(dk, database),    }}/// Whether `key` is `database`'s photo, video, book, song, film, recording or kept chat picture file.pub fn is_person_file(database: &str, key: &str) -> bool {    let mut parts = key.splitn(3, '/');    matches!((parts.next(), parts.next(), parts.next()), (Some(db), Some(kind), Some(rest)) if db == database && !rest.is_empty() && SEALED_KINDS.contains(&kind))}/// Whether the file at `path` starts as an f1 file does.pub fn looks_sealed(path: &Path) -> std::io::Result<bool> {    let mut head = [0u8; 4];    let mut f = std::fs::File::open(path)?;    let mut got = 0;    while got < 4 {        match f.read(&mut head[got..])? {            0 => break,            n => got += n,        }    }    Ok(got == 4 && (&head == file::MAGIC || arrival_file::is_arrival_file(&head)))}/// The sha256 a key's name says, when it names one (`…/<64 hex>.<ext>`).fn named_sha(key: &str) -> Option<&str> {    let name = key.rsplit('/').next()?;    let stem = name.split('.').next()?;    (stem.len() == 64 && stem.bytes().all(|b| b.is_ascii_hexdigit())).then_some(stem)}/// The file fetched into `raw` as the object keeps it, opened into `dest`: a/// sealed file with `fk`; a clear one only when its bytes are the ones its/// key names. `raw` goes either way; `dest` is left only when it opened.pub fn open_download(fk: &FileKey, key: &str, raw: &Path, dest: &Path) -> Result<(), String> {    let opened = (|| {        if looks_sealed(raw).map_err(|error| error.to_string())? {            // A file the object sealed at arrival is a device's f1 file past its head.            let start = arrival_head(raw)?.map_or(0, |(start, _)| start);            let len = std::fs::metadata(raw).map_err(|error| error.to_string())?.len().saturating_sub(start);            let mut inner = std::io::BufReader::new(std::fs::File::open(raw).map_err(|error| error.to_string())?);            inner.seek(SeekFrom::Start(start)).map_err(|error| error.to_string())?;            let sealed = Past { inner, start };            let mut reader = OpeningReader::new(fk, key, sealed, len).map_err(|error| error.code().to_string())?;            let mut out = std::fs::File::create(dest).map_err(|error| error.to_string())?;            std::io::copy(&mut reader, &mut out).map_err(|error| error.to_string())?;            out.flush().map_err(|error| error.to_string())?;            return Ok(());        }        open_clear(key, raw, dest)    })();    let _ = std::fs::remove_file(raw);    if opened.is_err() {        let _ = std::fs::remove_file(dest);    }    opened}/// A sealed file as plaintext, any range of it: `sealed` (Read + Seek over the/// sealed bytes, `sealed_len` long) opened for `key`.pub fn opening<S: Read + Seek>(fk: &FileKey, key: &str, sealed: S, sealed_len: u64) -> Result<OpeningReader<S>, String> {    OpeningReader::new(fk, key, sealed, sealed_len).map_err(|error| error.code().to_string())}#[cfg(test)]#[path = "sealed_tests.rs"]mod tests;