use crate::kvs::error::{KvsError, Result};
use crate::symmetric::implementation::{
decrypt_symmetric, derive_key_from_password, encrypt_symmetric,
};
use serde::{de::DeserializeOwned, Deserialize, Serialize};
use std::collections::HashMap;
use std::fs;
use std::path::PathBuf;
use std::sync::{Arc, Mutex};
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct KvPair {
pub key: String,
pub value: String,
}
#[derive(Clone)]
pub struct KvStore {
name: String,
path: PathBuf,
data: Arc<Mutex<HashMap<String, String>>>,
encrypted: bool,
password: Option<String>,
}
pub fn get_store_path() -> PathBuf {
let home_dir = dirs::home_dir().unwrap_or_else(|| PathBuf::from("."));
home_dir.join(".hero-vault").join("kvs")
}
pub fn create_store(name: &str, encrypted: bool, password: Option<&str>) -> Result<KvStore> {
if encrypted && password.is_none() {
return Err(KvsError::Other(
"Password required for encrypted store".to_string(),
));
}
let store_dir = get_store_path();
if !store_dir.exists() {
fs::create_dir_all(&store_dir)?;
}
let store_path = store_dir.join(format!("{}.json", name));
let store = KvStore {
name: name.to_string(),
path: store_path,
data: Arc::new(Mutex::new(HashMap::new())),
encrypted,
password: password.map(|s| s.to_string()),
};
store.save()?;
Ok(store)
}
pub fn open_store(name: &str, password: Option<&str>) -> Result<KvStore> {
let store_dir = get_store_path();
let store_path = store_dir.join(format!("{}.json", name));
if !store_path.exists() {
return Err(KvsError::StoreNotFound(name.to_string()));
}
let file_content = fs::read_to_string(&store_path)?;
let is_encrypted = !file_content.starts_with('{');
if is_encrypted && password.is_none() {
return Err(KvsError::Other(
"Password required for encrypted store".to_string(),
));
}
let data: HashMap<String, String> = if is_encrypted {
let password = password.unwrap();
let encrypted_data: Vec<u8> = serde_json::from_str(&file_content)?;
let key = derive_key_from_password(password);
let decrypted_data = decrypt_symmetric(&key, &encrypted_data)?;
let decrypted_str = String::from_utf8(decrypted_data)
.map_err(|e| KvsError::Deserialization(e.to_string()))?;
serde_json::from_str(&decrypted_str)?
} else {
serde_json::from_str(&file_content)?
};
let store = KvStore {
name: name.to_string(),
path: store_path,
data: Arc::new(Mutex::new(data)),
encrypted: is_encrypted,
password: password.map(|s| s.to_string()),
};
Ok(store)
}
pub fn delete_store(name: &str) -> Result<()> {
let store_dir = get_store_path();
let store_path = store_dir.join(format!("{}.json", name));
if !store_path.exists() {
return Err(KvsError::StoreNotFound(name.to_string()));
}
fs::remove_file(store_path)?;
Ok(())
}
pub fn list_stores() -> Result<Vec<String>> {
let store_dir = get_store_path();
if !store_dir.exists() {
return Ok(Vec::new());
}
let mut stores = Vec::new();
for entry in fs::read_dir(store_dir)? {
let entry = entry?;
let path = entry.path();
if path.is_file() && path.extension().map_or(false, |ext| ext == "json") {
if let Some(name) = path.file_stem() {
if let Some(name_str) = name.to_str() {
stores.push(name_str.to_string());
}
}
}
}
Ok(stores)
}
impl KvStore {
fn save(&self) -> Result<()> {
let data = self.data.lock().unwrap();
let serialized = serde_json::to_string(&*data)?;
if self.encrypted {
if let Some(password) = &self.password {
let key = derive_key_from_password(password);
let encrypted_data = encrypt_symmetric(&key, serialized.as_bytes())?;
let encrypted_json = serde_json::to_string(&encrypted_data)?;
fs::write(&self.path, encrypted_json)?;
} else {
return Err(KvsError::Other(
"Password required for encrypted store".to_string(),
));
}
} else {
fs::write(&self.path, serialized)?;
}
Ok(())
}
pub fn set<K, V>(&self, key: K, value: &V) -> Result<()>
where
K: ToString,
V: Serialize,
{
let key_str = key.to_string();
let serialized = serde_json::to_string(value)?;
{
let mut data = self.data.lock().unwrap();
data.insert(key_str, serialized);
}
self.save()?;
Ok(())
}
pub fn get<K, V>(&self, key: K) -> Result<V>
where
K: ToString,
V: DeserializeOwned,
{
let key_str = key.to_string();
let data = self.data.lock().unwrap();
match data.get(&key_str) {
Some(serialized) => {
let value: V = serde_json::from_str(serialized)?;
Ok(value)
}
None => Err(KvsError::KeyNotFound(key_str)),
}
}
pub fn delete<K>(&self, key: K) -> Result<()>
where
K: ToString,
{
let key_str = key.to_string();
{
let mut data = self.data.lock().unwrap();
if data.remove(&key_str).is_none() {
return Err(KvsError::KeyNotFound(key_str));
}
}
self.save()?;
Ok(())
}
pub fn contains<K>(&self, key: K) -> Result<bool>
where
K: ToString,
{
let key_str = key.to_string();
let data = self.data.lock().unwrap();
Ok(data.contains_key(&key_str))
}
pub fn keys(&self) -> Result<Vec<String>> {
let data = self.data.lock().unwrap();
Ok(data.keys().cloned().collect())
}
pub fn clear(&self) -> Result<()> {
{
let mut data = self.data.lock().unwrap();
data.clear();
}
self.save()?;
Ok(())
}
pub fn name(&self) -> &str {
&self.name
}
pub fn is_encrypted(&self) -> bool {
self.encrypted
}
}