use crate::db;
use crate::error::{Error, Result};
use crate::format;
use crate::model::{Item, ItemSummary, NewItem, Payload, Query};
use rusqlite::Connection;
use std::fs;
use std::io::Write;
use std::path::{Path, PathBuf};
use std::time::{SystemTime, UNIX_EPOCH};
use zeroize::Zeroizing;
pub struct Vault {
path: PathBuf,
password: Zeroizing<Vec<u8>>,
connection: Connection,
}
impl Vault {
pub fn create(path: impl AsRef<Path>, password: &[u8]) -> Result<Self> {
let path = path.as_ref().to_path_buf();
if path.exists() {
return Err(Error::AlreadyExists(path));
}
let vault = Self {
path,
password: Zeroizing::new(password.to_vec()),
connection: db::create()?,
};
vault.save()?;
Ok(vault)
}
pub fn open(path: impl AsRef<Path>, password: &[u8]) -> Result<Self> {
let path = path.as_ref().to_path_buf();
let file = fs::read(&path)
.map_err(|source| Error::io(format!("cannot read {}", path.display()), source))?;
let database = format::decode(password, &file)?;
Ok(Self {
path,
password: Zeroizing::new(password.to_vec()),
connection: db::load(&database)?,
})
}
pub fn path(&self) -> &Path {
&self.path
}
pub fn save(&self) -> Result<()> {
let database = Zeroizing::new(db::dump(&self.connection)?);
let sealed = format::encode(&self.password, &database)?;
write_atomically(&self.path, &sealed)
}
pub fn add(&mut self, item: NewItem) -> Result<i64> {
db::insert_item(&mut self.connection, item, now())
}
pub fn add_existing(
&mut self,
item: NewItem,
uuid: &str,
created_at: i64,
updated_at: i64,
) -> Result<i64> {
db::insert_item_with_uuid(&mut self.connection, item, uuid, created_at, updated_at)
}
pub fn find_by_uuid(&self, uuid: &str) -> Result<Option<i64>> {
db::find_by_uuid(&self.connection, uuid)
}
pub fn get(&self, id: i64) -> Result<Item> {
db::get_item(&self.connection, id)
}
pub fn summary(&self, id: i64) -> Result<ItemSummary> {
db::get_summary(&self.connection, id)
}
pub fn update(
&mut self,
id: i64,
title: Option<String>,
payload: Option<Payload>,
tags: Option<Vec<String>>,
) -> Result<()> {
db::update_item(&mut self.connection, id, title, payload, tags, now())
}
pub fn remove(&mut self, id: i64) -> Result<()> {
db::delete_item(&self.connection, id)
}
pub fn search(&self, query: &Query) -> Result<Vec<ItemSummary>> {
db::search(&self.connection, query)
}
pub fn list(&self) -> Result<Vec<ItemSummary>> {
db::search(&self.connection, &Query::all())
}
pub fn tags(&self) -> Result<Vec<(String, i64)>> {
db::list_tags(&self.connection)
}
pub fn resolve(&self, reference: &str) -> Result<ItemSummary> {
let reference = reference.trim();
if reference.is_empty() {
return Err(Error::NotFound(String::new()));
}
if let Ok(id) = reference.parse::<i64>() {
match self.summary(id) {
Ok(summary) => return Ok(summary),
Err(Error::ItemNotFound(_)) => {}
Err(other) => return Err(other),
}
}
let matches = self.search(&Query::all().text(reference))?;
let exact: Vec<ItemSummary> = matches
.iter()
.filter(|summary| summary.title.eq_ignore_ascii_case(reference))
.cloned()
.collect();
let candidates = if exact.is_empty() { matches } else { exact };
match candidates.len() {
0 => Err(Error::NotFound(reference.to_owned())),
1 => Ok(candidates.into_iter().next().expect("length checked")),
_ => Err(Error::Ambiguous {
reference: reference.to_owned(),
candidates,
}),
}
}
pub fn change_password(&mut self, password: &[u8]) -> Result<()> {
self.password = Zeroizing::new(password.to_vec());
self.save()
}
}
impl std::fmt::Debug for Vault {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("Vault")
.field("path", &self.path)
.field("password", &"<redacted>")
.finish_non_exhaustive()
}
}
pub(crate) fn now() -> i64 {
SystemTime::now()
.duration_since(UNIX_EPOCH)
.map(|elapsed| elapsed.as_secs() as i64)
.unwrap_or(0)
}
fn write_atomically(path: &Path, bytes: &[u8]) -> Result<()> {
let directory = path.parent().filter(|p| !p.as_os_str().is_empty());
if let Some(directory) = directory {
fs::create_dir_all(directory).map_err(|source| {
Error::io(format!("cannot create {}", directory.display()), source)
})?;
}
let temporary = temporary_path(path);
let write = || -> std::io::Result<()> {
let mut file = fs::File::create(&temporary)?;
file.write_all(bytes)?;
file.sync_all()
};
if let Err(source) = write() {
let _ = fs::remove_file(&temporary);
return Err(Error::io(
format!("cannot write {}", temporary.display()),
source,
));
}
if let Err(source) = fs::rename(&temporary, path) {
let _ = fs::remove_file(&temporary);
return Err(Error::io(
format!("cannot replace {}", path.display()),
source,
));
}
Ok(())
}
fn temporary_path(path: &Path) -> PathBuf {
let mut name = path
.file_name()
.unwrap_or_else(|| std::ffi::OsStr::new("vault"))
.to_os_string();
name.push(".sefy-tmp");
path.with_file_name(name)
}