166 lines
5.1 KiB
Rust
166 lines
5.1 KiB
Rust
use std::fs;
|
|
use std::sync::Mutex;
|
|
use argon2::{Algorithm, Argon2, Version, Error as Argon2Error, ParamsBuilder};
|
|
use base64ct::{Base64, Encoding};
|
|
use duckdb::{
|
|
Connection,
|
|
params,
|
|
Error,
|
|
};
|
|
|
|
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))]
|
|
const MEM_COST: u32 = 128 * 1024;
|
|
#[cfg(not(debug_assertions))]
|
|
const TIME_COST: u32 = 8;
|
|
#[cfg(not(debug_assertions))]
|
|
const PARALLELISM_COST: u32 = 4;
|
|
|
|
#[cfg(debug_assertions)]
|
|
const MEM_COST: u32 = 1024;
|
|
#[cfg(debug_assertions)]
|
|
const TIME_COST: u32 = 1;
|
|
#[cfg(debug_assertions)]
|
|
const PARALLELISM_COST: u32 = 1;
|
|
|
|
|
|
#[derive(Debug)]
|
|
pub struct Db {
|
|
connection: Mutex<Connection>,
|
|
}
|
|
|
|
impl Db {
|
|
/// Connect to the database, creating it if necessary.
|
|
pub fn connect(config: &AppConfig, passphrase: &str) -> Result<Self, CreddyError> {
|
|
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()?;
|
|
// hard-code the path for now, until we get proper config set up
|
|
conn.execute(
|
|
"ATTACH ? AS creddy (ENCRYPTION_KEY ?);",
|
|
params![path, key],
|
|
)?;
|
|
conn.execute("USE creddy;", [])?;
|
|
Ok(Self{ connection: Mutex::new(conn) })
|
|
}
|
|
|
|
/// Hash the given passphrase/salt with argon2, then encode to base64 for DuckDB
|
|
fn derive_key(passphrase: &str, salt: &[u8; 32]) -> Result<String, Argon2Error> {
|
|
let params = ParamsBuilder::new()
|
|
.m_cost(MEM_COST)
|
|
.t_cost(TIME_COST)
|
|
.p_cost(PARALLELISM_COST)
|
|
.build()
|
|
.unwrap(); // only errors if the given params are invalid
|
|
|
|
let hasher = Argon2::new(Algorithm::Argon2id, Version::V0x13, params);
|
|
|
|
let mut key = [0; 32]; // todo: replace this with a `zeroize` or `secrecy` type
|
|
hasher.hash_password_into(passphrase.as_bytes(), salt, &mut key)?;
|
|
|
|
Ok(Base64::encode_string(&key))
|
|
}
|
|
}
|
|
|
|
|
|
#[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 = "YvOfk7EXGX+SnvdGySbTtf8OXAXg3AGikvKxJOLkLOo=";
|
|
|
|
#[test]
|
|
fn test_connect_new() -> TestResult {
|
|
let data_dir = tempfile::tempdir()?;
|
|
let config = AppConfig {
|
|
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(&config.db_path()) {
|
|
Err(Error::DuckDBFailure(error, _desc)) => {
|
|
assert!(error.code == duckdb::ErrorCode::Unknown);
|
|
assert!(error.extended_code == 1);
|
|
},
|
|
Err(e) => panic!("Unexpected error type: {e:?}"),
|
|
Ok(_) => panic!("Should not be able to open newly-created database without encryption key"),
|
|
};
|
|
|
|
// confirm that using a different passphrase won't work
|
|
let res = Db::connect(&config, "not the correct passphrase");
|
|
match res {
|
|
Err(CreddyError::Db(Error::DuckDBFailure(error, Some(desc)))) => {
|
|
assert!(error.code == duckdb::ErrorCode::Unknown);
|
|
assert!(error.extended_code == 1);
|
|
assert!(desc.contains("Wrong encryption key"));
|
|
},
|
|
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() -> TestResult {
|
|
let data_dir = tempfile::tempdir()?;
|
|
let config = AppConfig {
|
|
data_dir: data_dir.path().to_path_buf(),
|
|
db_salt: [0u8; 32],
|
|
};
|
|
|
|
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_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(())
|
|
}
|
|
}
|