From a10510ed6ef448bbb29cbe730588db2eb70b08e1 Mon Sep 17 00:00:00 2001 From: Joseph Montanaro Date: Fri, 13 Nov 2026 13:43:06 -0500 Subject: [PATCH] persist database salt and rework config loading --- .cargo/config.toml | 3 + .gitignore | 4 +- Cargo.lock | 19 ++--- Cargo.toml | 2 +- src/config.rs | 180 ++++++++++++++++++++++++++++++++------- src/db/config.rs | 9 ++ src/{db.rs => db/mod.rs} | 80 +++++++++++------ src/error.rs | 4 + src/session.rs | 2 +- 9 files changed, 227 insertions(+), 76 deletions(-) create mode 100644 .cargo/config.toml create mode 100644 src/db/config.rs rename src/{db.rs => db/mod.rs} (67%) diff --git a/.cargo/config.toml b/.cargo/config.toml new file mode 100644 index 0000000..4c0fbdc --- /dev/null +++ b/.cargo/config.toml @@ -0,0 +1,3 @@ +[env] +# in development (i.e. when running through Cargo), store state in project directory +CREDDY_DATA_DIR = { value = "data", relative = true } diff --git a/.gitignore b/.gitignore index a228b20..b627e42 100644 --- a/.gitignore +++ b/.gitignore @@ -1,6 +1,6 @@ **/creddy.db -# .env is system-specific -.env +# state directory for development work +data/ .vscode pacman/pkg diff --git a/Cargo.lock b/Cargo.lock index 697983a..6269b7a 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1373,10 +1373,10 @@ dependencies = [ "getrandom 0.4.3", "gpui-kit", "gpui-omarchy", - "is-terminal", "serde", "serde_json", "tempfile", + "testresult", "thiserror 2.0.21", ] @@ -3556,17 +3556,6 @@ dependencies = [ "once_cell", ] -[[package]] -name = "is-terminal" -version = "0.4.17" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3640c1c38b8e4e43584d8df18be5fc6b0aa314ce6ebf51b53313d4306cca8e46" -dependencies = [ - "hermit-abi", - "libc", - "windows-sys 0.61.2", -] - [[package]] name = "is-wsl" version = "0.4.0" @@ -6735,6 +6724,12 @@ dependencies = [ "winapi-util", ] +[[package]] +name = "testresult" +version = "0.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9ad5f489c3aa16cefe5a90ee2d0390b1f8b31065a9a6694b36d85f2b96da7b27" + [[package]] name = "thiserror" version = "1.0.69" diff --git a/Cargo.toml b/Cargo.toml index 182fa93..2b8c734 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -16,9 +16,9 @@ duckdb = { version = "1.20000.1", features = ["bundled"] } getrandom = { version = "0.4.3", features = ["sys_rng"] } gpui-kit = "0.7.0" gpui-omarchy = "0.2.1" -is-terminal = "0.4.17" serde = "1.0.229" serde_json = "1.0.154" +testresult = "0.4.2" thiserror = "2.0.21" [dev-dependencies] diff --git a/src/config.rs b/src/config.rs index b0de9d7..7836b0b 100644 --- a/src/config.rs +++ b/src/config.rs @@ -1,8 +1,9 @@ +use std::env::{self, VarError}; +use std::ffi::OsString; use std::fs::File; -use std::path::PathBuf; +use std::path::{Path, PathBuf}; use gpui_kit::Global; -use is_terminal::IsTerminal; use serde::{Serialize, Deserialize}; use crate::error::CreddyError; @@ -11,80 +12,193 @@ use crate::error::CreddyError; /// Config that doesn't need to or can't be stored in the encrypted db /// (such as settings that must be known at startup, before unlock). #[derive(Debug, Clone, Serialize, Deserialize)] -struct PublicConfig { +pub struct PublicConfig { db_salt: [u8; 32], } impl PublicConfig { /// Construct a PublicConfig with default values, in case there is nothing saved on disk - fn default() -> PublicConfig { + pub fn default() -> PublicConfig { let mut db_salt = [0u8; 32]; let _ = getrandom::fill(&mut db_salt); PublicConfig { db_salt } } /// Load non-sensitive config from disk. - fn load() -> Result { - let public_path = config_path()?.join("public_config.json"); - if public_path.exists() { - let f = File::open(public_path)?; + pub fn load(path: &Path) -> Result { + if path.exists() { + let f = File::open(path)?; serde_json::from_reader(f).map_err(|e| CreddyError::ConfigDecode(e)) } else { Ok(PublicConfig::default()) } } + + pub fn save(&self, path: &Path) -> Result<(), CreddyError> { + let file = File::create(path)?; + serde_json::to_writer(file, self)?; + Ok(()) + } } #[derive(Debug, Clone)] pub struct AppConfig { - pub db_path: PathBuf, + pub data_dir: PathBuf, pub db_salt: [u8; 32], } impl AppConfig { /// Load config from disk, using defaults for non-public values. pub fn load() -> Result { - let public_config = PublicConfig::load()?; + let data_dir = AppConfig::resolve_data_dir( + env::var_os("CREDDY_DATA_DIR"), + dirs::data_dir(), + )?; + + AppConfig::load_from(data_dir) + } + + fn load_from(data_dir: PathBuf) -> Result { + let public_config = PublicConfig::load(&data_dir.join("public_config.json"))?; Ok(AppConfig { - db_path: db_path()?, + data_dir, db_salt: public_config.db_salt, }) } + + fn resolve_data_dir(creddy_data_dir: Option, platform_data_dir: Option) -> Result { + creddy_data_dir + .map(PathBuf::from) + .or_else(|| platform_data_dir.map(|d| d.join("creddy"))) + .ok_or(CreddyError::DataDirNotFound) + } + + pub fn public_config_path(&self) -> PathBuf { + self.data_dir.join("public_config.json") + } + + pub fn db_path(&self) -> PathBuf { + self.data_dir.join("creddy.duckdb") + } + + pub fn public_config(&self) -> PublicConfig { + PublicConfig { + db_salt: self.db_salt, + } + } } impl Global for AppConfig {} -pub fn config_path() -> Result { - dirs::data_dir() - .map(|d| d.join("creddy")) - .ok_or(CreddyError::DataDirNotFound) -} - - -pub fn db_path() -> Result { - let dir = config_path()?; - std::fs::create_dir_all(&dir)?; - - let path = if cfg!(debug_assertions) && std::io::stdout().is_terminal() { - dir.join("creddy.dev.duckdb") - } - else { - dir.join("creddy.duckdb") - }; - - Ok(path) -} - - #[cfg(test)] mod tests { use super::*; + use tempfile::NamedTempFile; + use testresult::TestResult; #[test] fn test_public_default() { let conf = PublicConfig::default(); assert!(conf.db_salt.len() == 32); } + + #[test] + fn test_public_config_load_not_present() -> TestResult { + let p = tempfile::tempdir()?.path().join("public_config.json"); + let conf = PublicConfig::load(&p)?; + assert!(conf.db_salt.len() == 32); + Ok(()) + } + + #[test] + fn test_public_config_load_present() -> TestResult { + let data_dir = tempfile::tempdir()?; + let p = data_dir.path().join("public_config.json"); + let expected = PublicConfig::default(); // uses a random db salt + let f = File::create(&p)?; + serde_json::to_writer(f, &expected)?; + + let loaded = PublicConfig::load(&p)?; + assert!(loaded.db_salt == expected.db_salt); + Ok(()) + } + + #[test] + fn test_config_load_not_present() -> TestResult { + let data_dir = tempfile::tempdir()?; + let config = AppConfig::load_from(data_dir.path().to_path_buf())?; + assert!(config.data_dir == data_dir.path()); + assert!(config.db_salt.len() == 32); + Ok(()) + } + + #[test] + fn test_config_load_present() -> TestResult { + let data_dir = tempfile::tempdir()?; + let p = data_dir.path().join("public_config.json"); + let public = PublicConfig::default(); // uses a random db salt + let f = File::create(&p)?; + serde_json::to_writer(f, &public)?; + + let config = AppConfig::load_from(data_dir.path().to_path_buf())?; + assert!(config.data_dir == data_dir.path()); + assert!(config.db_salt == public.db_salt); + Ok(()) + } + + #[test] + fn test_resolve_data_dir_override() -> TestResult { + let data_dir = AppConfig::resolve_data_dir( + Some(OsString::from("/tmp/creddy")), + None, + )?; + assert!(data_dir == PathBuf::from("/tmp/creddy")); + Ok(()) + } + + #[test] + fn test_resolve_data_dir_default() -> TestResult { + let data_dir = AppConfig::resolve_data_dir( + None, + Some(PathBuf::from("/tmp")), + )?; + + assert!(data_dir == PathBuf::from("/tmp/creddy")); + Ok(()) + } + + #[test] + fn test_config_paths() { + let config = AppConfig { + data_dir: PathBuf::from("/tmp/creddy"), + db_salt: PublicConfig::default().db_salt, + }; + + assert!(config.db_path() == PathBuf::from("/tmp/creddy/creddy.duckdb")); + assert!(config.public_config_path() == PathBuf::from("/tmp/creddy/public_config.json")); + } + + #[test] + fn test_public_config_from_app_config() { + let config = AppConfig { + data_dir: PathBuf::from("/tmp/creddy"), + db_salt: PublicConfig::default().db_salt, + }; + + let public = config.public_config(); + assert!(public.db_salt == config.db_salt); + } + + #[test] + fn test_public_config_save_load() -> TestResult { + let file = NamedTempFile::new()?; + let expected = PublicConfig::default(); + expected.save(file.path())?; + + let loaded = PublicConfig::load(file.path())?; + assert!(loaded.db_salt == expected.db_salt); + Ok(()) + } } diff --git a/src/db/config.rs b/src/db/config.rs new file mode 100644 index 0000000..f10d075 --- /dev/null +++ b/src/db/config.rs @@ -0,0 +1,9 @@ +use crate::config::AppConfig; +use crate::error::CreddyError; +use super::Db; + +impl Db { + pub fn save_config(&self, config: &AppConfig) -> Result<(), CreddyError> { + todo!() + } +} diff --git a/src/db.rs b/src/db/mod.rs similarity index 67% rename from src/db.rs rename to src/db/mod.rs index b5d113a..6bdb202 100644 --- a/src/db.rs +++ b/src/db/mod.rs @@ -1,3 +1,4 @@ +use std::fs; use std::sync::Mutex; use argon2::{Algorithm, Argon2, Version, Error as Argon2Error, ParamsBuilder}; use base64ct::{Base64, Encoding}; @@ -10,6 +11,7 @@ use duckdb::{ use crate::error::CreddyError; use crate::config::AppConfig; +mod config; // tests take forever with production parameters, so we turn them down in dev #[cfg(not(debug_assertions))] @@ -20,7 +22,7 @@ const TIME_COST: u32 = 8; const PARALLELISM_COST: u32 = 4; #[cfg(debug_assertions)] -const MEM_COST: u32 = 48 * 1024; +const MEM_COST: u32 = 1024; #[cfg(debug_assertions)] const TIME_COST: u32 = 1; #[cfg(debug_assertions)] @@ -33,8 +35,16 @@ pub struct Db { } impl Db { + /// Connect to the database, creating it if necessary. pub fn connect(config: &AppConfig, passphrase: &str) -> Result { - let path = config.db_path.to_string_lossy(); + fs::create_dir_all(&config.data_dir)?; + // since we are about to make use of the salt stored in `config`, we need to save it now + config.public_config().save(&config.public_config_path())?; + + let path = config.db_path() + .into_os_string() + .into_string() + .map_err(|s| CreddyError::InvalidPath(s))?; let key = Db::derive_key(passphrase, &config.db_salt)?; let conn = Connection::open_in_memory()?; @@ -68,27 +78,26 @@ impl Db { #[cfg(test)] mod tests { + use testresult::TestResult; use super::*; const TEST_PASSPHRASE: &'static str = "correct horse battery staple"; const TEST_SALT: [u8; 32] = [0; 32]; // the result of hashing TEST_PASSPHRASE with TEST_SALT and encoding to Base64 - const TEST_KEY: &'static str = "CPLL6XQdzFMlhx1yOKX461hvsDOSD27a8AwEo4jyV7Q="; + const TEST_KEY: &'static str = "YvOfk7EXGX+SnvdGySbTtf8OXAXg3AGikvKxJOLkLOo="; #[test] - fn test_connect_new() { - let data_dir = tempfile::tempdir().unwrap(); - let db_path = data_dir.path().join("creddy.test.db"); - + fn test_connect_new() -> TestResult { + let data_dir = tempfile::tempdir()?; let config = AppConfig { - db_path: db_path.clone(), + data_dir: data_dir.path().to_path_buf(), db_salt: [0u8; 32], }; let res = Db::connect(&config, TEST_PASSPHRASE); assert!(res.is_ok()); // confirm that db is in fact encrypted - match Connection::open(&db_path) { + match Connection::open(&config.db_path()) { Err(Error::DuckDBFailure(error, _desc)) => { assert!(error.code == duckdb::ErrorCode::Unknown); assert!(error.extended_code == 1); @@ -108,32 +117,49 @@ mod tests { Err(e) => panic!("Unexpected error type: {e:?}"), Ok(_) => panic!("Should not be able to open database with a different passphrase"), } + + Ok(()) } #[test] - fn test_connect_existing() { - let data_dir = tempfile::tempdir().unwrap(); - let db_path = data_dir.path().join("creddy.test.db"); - - let conn = Connection::open_in_memory().unwrap(); - conn.execute( - "ATTACH ? AS creddy (ENCRYPTION_KEY ?);", - params![&db_path.to_string_lossy(), TEST_KEY], - ).unwrap(); - + fn test_connect_existing() -> TestResult { + let data_dir = tempfile::tempdir()?; let config = AppConfig { - db_path, + data_dir: data_dir.path().to_path_buf(), db_salt: [0u8; 32], }; - let res = Db::connect(&config, TEST_PASSPHRASE); - assert!(res.is_ok()); + + let conn = Connection::open_in_memory()?; + conn.execute( + "ATTACH ? AS creddy (ENCRYPTION_KEY ?);", + params![&config.db_path().to_string_lossy(), TEST_KEY], + )?; + + Db::connect(&config, TEST_PASSPHRASE)?; + Ok(()) } #[test] - fn test_derive_key() { - match Db::derive_key(TEST_PASSPHRASE, &TEST_SALT) { - Ok(key) => assert!(key == "CPLL6XQdzFMlhx1yOKX461hvsDOSD27a8AwEo4jyV7Q="), - Err(e) => panic!("Error deriving key: {e}"), - } + fn test_connect_create_dir() -> TestResult { + let tmp_dir = tempfile::tempdir()?; + let data_dir = tmp_dir.path().join("creddy"); + + // data_dir does not exist at this point + let config = AppConfig { + data_dir, + db_salt: TEST_SALT, + }; + + Db::connect(&config, TEST_PASSPHRASE)?; + Ok(()) + } + + #[test] + fn test_derive_key() -> TestResult { + let key = Db::derive_key(TEST_PASSPHRASE, &TEST_SALT)?; + dbg!(&key); + dbg!(TEST_KEY); + assert!(key == TEST_KEY); + Ok(()) } } diff --git a/src/error.rs b/src/error.rs index a6c39f4..f683e7a 100644 --- a/src/error.rs +++ b/src/error.rs @@ -1,3 +1,4 @@ +use std::ffi::OsString; use thiserror::Error; @@ -6,6 +7,9 @@ pub enum CreddyError { #[error("Couldn't determine location for app state")] DataDirNotFound, + #[error("Invalid path: {0:?}")] + InvalidPath(OsString), + #[error("Error from database: {0}")] Db(#[from] duckdb::Error), diff --git a/src/session.rs b/src/session.rs index 8ac65bb..65dd219 100644 --- a/src/session.rs +++ b/src/session.rs @@ -12,7 +12,7 @@ pub enum AppSession { impl AppSession { pub fn load(config: &AppConfig) -> AppSession { - if config.db_path.exists() { + if config.db_path().exists() { AppSession::Locked } else { AppSession::Empty