Cotton code
116 lines · 6.0 KB · RustRaw
//! This Mac as a device that holds the person's data key, for the tools run//! from a shell (`music-import`, `seal-files`, `reseal-files`): the same//! standing the app's pass gives its sources.//!//! A tool signs in as a device (`seal-device` keeps the credential in a file,//! mode 600), is approved once from the phone, and from then on opens the//! vault with the key in the login Keychain (or the key file a shell tool was//! pointed at), opens the data key from the object's `seal_key` row, and//! writes through a client whose rows go sealed through the importer's copy//! ([`crate::copy::SealDoor`]) and whose files go sealed under the person's//! file keys ([`cotton_client::media::sealed::PersonFiles`]). Nothing is ever//! sent open, and no key is printed, written or sent.use std::path::{Path, PathBuf};use std::sync::Arc;use cotton_client::media::sealed::PersonFiles;use cotton_client::seal::{DataKeyStore, HeldDataKeys};use crate::copy::{Copy, SealDoor};use crate::object::{ObjectClient, ObjectError};use crate::patience::Patience;use crate::seal_migrate::{data_key_row, ObjectLine};use crate::vault::{tool_keyring, ImporterVault, Keyring, VaultError};/// What names this Mac to a tool: `--base --device-id --token-file [--key-file] [--data-dir]`.#[derive(Debug, Clone, Default)]pub struct DeviceArgs {    pub base: Option<String>,    pub device_id: Option<String>,    pub token_file: Option<PathBuf>,    pub key_file: Option<PathBuf>,    pub data_dir: Option<PathBuf>,}impl DeviceArgs {    pub const USAGE: &'static str = "--base <url> --device-id <id> --token-file <device credential file> [--key-file <path>] [--data-dir <dir>]";    /// Take `flag value` when it is one of this Mac's; `false` when it is not.    pub fn take(&mut self, flag: &str, value: &str) -> bool {        match flag {            "--base" => self.base = Some(value.trim_end_matches('/').to_string()),            "--device-id" => self.device_id = Some(value.to_string()),            "--token-file" => self.token_file = Some(PathBuf::from(value)),            "--key-file" => self.key_file = Some(PathBuf::from(value)),            "--data-dir" => self.data_dir = Some(PathBuf::from(value)),            _ => return false,        }        true    }    /// Open this Mac on its object. The credential is the device's own    /// (`ctd_…`, from `seal-device`): an assistant's `ctn_` token holds no    /// key and is refused by name.    pub fn open(&self) -> Result<Device, String> {        let base = self.base.clone().ok_or("--base is needed")?;        if !(base.starts_with("https://") || base.starts_with("http://")) {            return Err("--base is the object's address, http(s)://…".to_string());        }        let device_id = self.device_id.clone().ok_or("--device-id is needed (the id seal-device signed this Mac in under)")?;        let token_file = self.token_file.clone().ok_or("--token-file is needed")?;        let token = std::fs::read_to_string(&token_file).map_err(|_| format!("--token-file {} cannot be read", token_file.display()))?.trim().to_string();        if token.starts_with("ctn_") {            return Err(format!("--token-file {} holds an assistant's token, which holds no key: name the device credential seal-device kept", token_file.display()));        }        let object = ObjectClient::new(base, Some(token)).map_err(|e| e.to_string())?;        let keyring = tool_keyring(&device_id, self.key_file.as_deref());        Device::open(object, &device_id, keyring.as_ref(), self.data_dir.as_deref())    }}/// This Mac, its vault opened and the data key held for the tool's run.pub struct Device {    /// The object: rows to sealed tables go sealed, a person's files go sealed.    pub object: ObjectClient,    pub database_id: String,    pub keys: Arc<HeldDataKeys>,    pub files: Arc<PersonFiles>,    /// Holds the copy's folder when the tool named none.    _scratch: Option<tempfile::TempDir>,}impl Device {    /// `object` holds the device's credential; `data_dir` keeps the    /// importer's copy between runs (a scratch folder when none is named).    pub fn open(object: ObjectClient, device_id: &str, keyring: &dyn Keyring, data_dir: Option<&Path>) -> Result<Device, String> {        // Opening is three reads of the object: one that is away for a few minutes is waited for, as a send is.        let patience = Patience::default();        let database_id = patience.run(|| object.database_id()).map_err(|e| format!("the object's database id could not be read: {e}"))?;        let vault = ImporterVault::new(keyring, device_id, "");        let open = patience            .attempt(|| vault.open_only(&object), |e| matches!(e, VaultError::Object(away) if ObjectError::is_passing(away)))            .map_err(|e| e.to_string())?            .ok_or("vault_locked: this Mac's vault is not open (no key in the Keychain, or the phone has not approved this Mac yet): run seal-device and approve it")?;        let dk = open.data_key(&data_key_row(&mut ObjectLine::patient(&object, &patience))?).map_err(|e| format!("{}: the data key did not open ({e})", e.code()))?;        drop(open);        let keys = HeldDataKeys::new();        keys.hold(&database_id, &dk);        let (scratch, dir) = match data_dir {            Some(dir) => {                std::fs::create_dir_all(dir).map_err(|e| format!("{}: {e}", dir.display()))?;                (None, dir.to_path_buf())            }            None => {                let scratch = tempfile::tempdir().map_err(|e| e.to_string())?;                let dir = scratch.path().to_path_buf();                (Some(scratch), dir)            }        };        let store: Arc<dyn DataKeyStore> = keys.clone();        let copy = Arc::new(Copy::open(&dir.join("copy.db"), &database_id, store.clone()).map_err(|e| e.to_string())?);        let files = Arc::new(PersonFiles::new(database_id.clone(), store));        let object = object.sealing_with(SealDoor::over(copy)).sealing_files(files.clone());        Ok(Device { object, database_id, keys, files, _scratch: scratch })    }}