persist database salt and rework config loading

This commit is contained in:
jfmonty2 committed 2026-11-13 13:43:06 -05:00
1 parent 2371486f39
commit a10510ed6e
9 files changed
+227 -76

No files matched your search

+3
View File
@@ -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 }
+2 -2
View File
@@ -1,6 +1,6 @@
**/creddy.db **/creddy.db
# .env is system-specific # state directory for development work
.env data/
.vscode .vscode
pacman/pkg pacman/pkg
Generated
+7 -12
View File
@@ -1373,10 +1373,10 @@ dependencies = [
"getrandom 0.4.3", "getrandom 0.4.3",
"gpui-kit", "gpui-kit",
"gpui-omarchy", "gpui-omarchy",
"is-terminal",
"serde", "serde",
"serde_json", "serde_json",
"tempfile", "tempfile",
"testresult",
"thiserror 2.0.21", "thiserror 2.0.21",
] ]
@@ -3556,17 +3556,6 @@ dependencies = [
"once_cell", "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]] [[package]]
name = "is-wsl" name = "is-wsl"
version = "0.4.0" version = "0.4.0"
@@ -6735,6 +6724,12 @@ dependencies = [
"winapi-util", "winapi-util",
] ]
[[package]]
name = "testresult"
version = "0.4.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9ad5f489c3aa16cefe5a90ee2d0390b1f8b31065a9a6694b36d85f2b96da7b27"
[[package]] [[package]]
name = "thiserror" name = "thiserror"
version = "1.0.69" version = "1.0.69"
+1 -1
View File
@@ -16,9 +16,9 @@ duckdb = { version = "1.20000.1", features = ["bundled"] }
getrandom = { version = "0.4.3", features = ["sys_rng"] } getrandom = { version = "0.4.3", features = ["sys_rng"] }
gpui-kit = "0.7.0" gpui-kit = "0.7.0"
gpui-omarchy = "0.2.1" gpui-omarchy = "0.2.1"
is-terminal = "0.4.17"
serde = "1.0.229" serde = "1.0.229"
serde_json = "1.0.154" serde_json = "1.0.154"
testresult = "0.4.2"
thiserror = "2.0.21" thiserror = "2.0.21"
[dev-dependencies] [dev-dependencies]
+147 -33
View File
@@ -1,8 +1,9 @@
use std::env::{self, VarError};
use std::ffi::OsString;
use std::fs::File; use std::fs::File;
use std::path::PathBuf; use std::path::{Path, PathBuf};
use gpui_kit::Global; use gpui_kit::Global;
use is_terminal::IsTerminal;
use serde::{Serialize, Deserialize}; use serde::{Serialize, Deserialize};
use crate::error::CreddyError; 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 /// 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). /// (such as settings that must be known at startup, before unlock).
#[derive(Debug, Clone, Serialize, Deserialize)] #[derive(Debug, Clone, Serialize, Deserialize)]
struct PublicConfig { pub struct PublicConfig {
db_salt: [u8; 32], db_salt: [u8; 32],
} }
impl PublicConfig { impl PublicConfig {
/// Construct a PublicConfig with default values, in case there is nothing saved on disk /// 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 mut db_salt = [0u8; 32];
let _ = getrandom::fill(&mut db_salt); let _ = getrandom::fill(&mut db_salt);
PublicConfig { db_salt } PublicConfig { db_salt }
} }
/// Load non-sensitive config from disk. /// Load non-sensitive config from disk.
fn load() -> Result<PublicConfig, CreddyError> { pub fn load(path: &Path) -> Result<PublicConfig, CreddyError> {
let public_path = config_path()?.join("public_config.json"); if path.exists() {
if public_path.exists() { let f = File::open(path)?;
let f = File::open(public_path)?;
serde_json::from_reader(f).map_err(|e| CreddyError::ConfigDecode(e)) serde_json::from_reader(f).map_err(|e| CreddyError::ConfigDecode(e))
} }
else { else {
Ok(PublicConfig::default()) 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)] #[derive(Debug, Clone)]
pub struct AppConfig { pub struct AppConfig {
pub db_path: PathBuf, pub data_dir: PathBuf,
pub db_salt: [u8; 32], pub db_salt: [u8; 32],
} }
impl AppConfig { impl AppConfig {
/// Load config from disk, using defaults for non-public values. /// Load config from disk, using defaults for non-public values.
pub fn load() -> Result<AppConfig, CreddyError> { pub fn load() -> Result<AppConfig, CreddyError> {
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<AppConfig, CreddyError> {
let public_config = PublicConfig::load(&data_dir.join("public_config.json"))?;
Ok(AppConfig { Ok(AppConfig {
db_path: db_path()?, data_dir,
db_salt: public_config.db_salt, db_salt: public_config.db_salt,
}) })
} }
fn resolve_data_dir(creddy_data_dir: Option<OsString>, platform_data_dir: Option<PathBuf>) -> Result<PathBuf, CreddyError> {
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 {} impl Global for AppConfig {}
pub fn config_path() -> Result<PathBuf, CreddyError> {
dirs::data_dir()
.map(|d| d.join("creddy"))
.ok_or(CreddyError::DataDirNotFound)
}
pub fn db_path() -> Result<PathBuf, CreddyError> {
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)] #[cfg(test)]
mod tests { mod tests {
use super::*; use super::*;
use tempfile::NamedTempFile;
use testresult::TestResult;
#[test] #[test]
fn test_public_default() { fn test_public_default() {
let conf = PublicConfig::default(); let conf = PublicConfig::default();
assert!(conf.db_salt.len() == 32); 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(())
}
} }
+9
View File
@@ -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!()
}
}
+53 -27
View File
@@ -1,3 +1,4 @@
use std::fs;
use std::sync::Mutex; use std::sync::Mutex;
use argon2::{Algorithm, Argon2, Version, Error as Argon2Error, ParamsBuilder}; use argon2::{Algorithm, Argon2, Version, Error as Argon2Error, ParamsBuilder};
use base64ct::{Base64, Encoding}; use base64ct::{Base64, Encoding};
@@ -10,6 +11,7 @@ use duckdb::{
use crate::error::CreddyError; use crate::error::CreddyError;
use crate::config::AppConfig; use crate::config::AppConfig;
mod config;
// tests take forever with production parameters, so we turn them down in dev // tests take forever with production parameters, so we turn them down in dev
#[cfg(not(debug_assertions))] #[cfg(not(debug_assertions))]
@@ -20,7 +22,7 @@ const TIME_COST: u32 = 8;
const PARALLELISM_COST: u32 = 4; const PARALLELISM_COST: u32 = 4;
#[cfg(debug_assertions)] #[cfg(debug_assertions)]
const MEM_COST: u32 = 48 * 1024; const MEM_COST: u32 = 1024;
#[cfg(debug_assertions)] #[cfg(debug_assertions)]
const TIME_COST: u32 = 1; const TIME_COST: u32 = 1;
#[cfg(debug_assertions)] #[cfg(debug_assertions)]
@@ -33,8 +35,16 @@ pub struct Db {
} }
impl Db { impl Db {
/// Connect to the database, creating it if necessary.
pub fn connect(config: &AppConfig, passphrase: &str) -> Result<Self, CreddyError> { pub fn connect(config: &AppConfig, passphrase: &str) -> Result<Self, CreddyError> {
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 key = Db::derive_key(passphrase, &config.db_salt)?;
let conn = Connection::open_in_memory()?; let conn = Connection::open_in_memory()?;
@@ -68,27 +78,26 @@ impl Db {
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use testresult::TestResult;
use super::*; use super::*;
const TEST_PASSPHRASE: &'static str = "correct horse battery staple"; const TEST_PASSPHRASE: &'static str = "correct horse battery staple";
const TEST_SALT: [u8; 32] = [0; 32]; const TEST_SALT: [u8; 32] = [0; 32];
// the result of hashing TEST_PASSPHRASE with TEST_SALT and encoding to Base64 // 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] #[test]
fn test_connect_new() { fn test_connect_new() -> TestResult {
let data_dir = tempfile::tempdir().unwrap(); let data_dir = tempfile::tempdir()?;
let db_path = data_dir.path().join("creddy.test.db");
let config = AppConfig { let config = AppConfig {
db_path: db_path.clone(), data_dir: data_dir.path().to_path_buf(),
db_salt: [0u8; 32], db_salt: [0u8; 32],
}; };
let res = Db::connect(&config, TEST_PASSPHRASE); let res = Db::connect(&config, TEST_PASSPHRASE);
assert!(res.is_ok()); assert!(res.is_ok());
// confirm that db is in fact encrypted // confirm that db is in fact encrypted
match Connection::open(&db_path) { match Connection::open(&config.db_path()) {
Err(Error::DuckDBFailure(error, _desc)) => { Err(Error::DuckDBFailure(error, _desc)) => {
assert!(error.code == duckdb::ErrorCode::Unknown); assert!(error.code == duckdb::ErrorCode::Unknown);
assert!(error.extended_code == 1); assert!(error.extended_code == 1);
@@ -108,32 +117,49 @@ mod tests {
Err(e) => panic!("Unexpected error type: {e:?}"), Err(e) => panic!("Unexpected error type: {e:?}"),
Ok(_) => panic!("Should not be able to open database with a different passphrase"), Ok(_) => panic!("Should not be able to open database with a different passphrase"),
} }
Ok(())
} }
#[test] #[test]
fn test_connect_existing() { fn test_connect_existing() -> TestResult {
let data_dir = tempfile::tempdir().unwrap(); let data_dir = tempfile::tempdir()?;
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();
let config = AppConfig { let config = AppConfig {
db_path, data_dir: data_dir.path().to_path_buf(),
db_salt: [0u8; 32], 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] #[test]
fn test_derive_key() { fn test_connect_create_dir() -> TestResult {
match Db::derive_key(TEST_PASSPHRASE, &TEST_SALT) { let tmp_dir = tempfile::tempdir()?;
Ok(key) => assert!(key == "CPLL6XQdzFMlhx1yOKX461hvsDOSD27a8AwEo4jyV7Q="), let data_dir = tmp_dir.path().join("creddy");
Err(e) => panic!("Error deriving key: {e}"),
} // 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(())
} }
} }
+4
View File
@@ -1,3 +1,4 @@
use std::ffi::OsString;
use thiserror::Error; use thiserror::Error;
@@ -6,6 +7,9 @@ pub enum CreddyError {
#[error("Couldn't determine location for app state")] #[error("Couldn't determine location for app state")]
DataDirNotFound, DataDirNotFound,
#[error("Invalid path: {0:?}")]
InvalidPath(OsString),
#[error("Error from database: {0}")] #[error("Error from database: {0}")]
Db(#[from] duckdb::Error), Db(#[from] duckdb::Error),
+1 -1
View File
@@ -12,7 +12,7 @@ pub enum AppSession {
impl AppSession { impl AppSession {
pub fn load(config: &AppConfig) -> AppSession { pub fn load(config: &AppConfig) -> AppSession {
if config.db_path.exists() { if config.db_path().exists() {
AppSession::Locked AppSession::Locked
} else { } else {
AppSession::Empty AppSession::Empty