use std::fs;
use std::io::Write as _;
use std::path::{Path, PathBuf};
use crate::crypto::{self, Key};
use crate::error::{Error, Result};
use crate::sanitize;
pub(crate) mod file_ops;
pub(crate) mod index_log;
pub(crate) mod keystore;
pub(crate) mod lock;
pub(crate) mod manifest;
pub(crate) mod migrate;
pub(crate) mod recovery;
pub(crate) mod rotation;
pub use keystore::KeyslotInfo;
pub use migrate::MigrationReport;
pub use recovery::RecoveryCode;
pub use rotation::RotationReport;
use file_ops as blobs;
use keystore::{KeyStore, VaultConfig};
use lock::VaultLock;
use manifest::{EntryMetadata, ManifestMap};
pub struct Vault {
path: PathBuf,
keystore: KeyStore,
}
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("unlocked", &self.keystore.is_unlocked())
.finish_non_exhaustive()
}
}
#[derive(Debug)]
pub enum BatchOp {
Add {
source: PathBuf,
name: Option<String>,
},
Replace {
source: PathBuf,
name: String,
},
Remove {
name: String,
},
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct IndexVersion {
pub generation: u64,
pub records: u64,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum WriteOutcome {
Applied {
version: IndexVersion,
},
Conflict {
current: IndexVersion,
},
}
#[derive(Debug, Clone)]
pub struct EntryInfo {
pub name: String,
pub size: u64,
pub is_directory: bool,
}
#[derive(Debug, Default, Clone)]
pub struct IntegrityReport {
pub total_entries: usize,
pub verified: usize,
pub missing: Vec<String>,
pub corrupted: Vec<String>,
}
impl Vault {
pub fn new(path: PathBuf) -> Self {
Self {
path,
keystore: KeyStore::new(),
}
}
pub fn exists(&self) -> bool {
self.config_path().exists()
}
pub fn path(&self) -> &Path {
&self.path
}
pub fn is_unlocked(&self) -> bool {
self.keystore.is_unlocked()
}
fn config_path(&self) -> PathBuf {
self.path.join("vault.config")
}
fn load_config(&self) -> Result<VaultConfig> {
let json = fs::read_to_string(self.config_path())?;
VaultConfig::parse(&json)
}
fn write_config(&self, config: &VaultConfig) -> Result<()> {
let json = serde_json::to_string_pretty(config).map_err(|_| Error::InvalidVault)?;
crate::fsutil::atomic_write(&self.config_path(), json.as_bytes())
}
pub fn init(&mut self, password: &str) -> Result<()> {
self.init_with_padding(password, crate::padding::Padding::None)
}
pub fn init_with_padding(
&mut self,
password: &str,
padding: crate::padding::Padding,
) -> Result<()> {
padding.validate()?;
if self.exists() {
return Err(Error::VaultExists);
}
crate::fsutil::create_private_dir(&self.path)?;
crate::fsutil::create_private_dir(&self.path.join("d"))?;
let _lock = self.lock_exclusive()?;
if self.exists() {
return Err(Error::VaultExists);
}
if self.path.join("vault.recovery").is_file() {
return Err(Error::VaultExists);
}
if self.path.join("d").join(".manifest.enc").is_file() {
return Err(Error::VaultExists);
}
let config = self.keystore.init(password)?;
manifest::init(&self.path, self.keystore.master_key()?, padding)?;
self.write_config(&config)?;
Ok(())
}
pub fn padding(&self) -> Result<crate::padding::Padding> {
let master = self.require_unlocked()?;
let _lock = self.lock_shared()?;
let (_files, padding) = manifest::load_with_padding(&self.path, &master)?;
Ok(padding)
}
pub fn version(&self) -> Result<IndexVersion> {
let master = self.require_unlocked()?;
let _lock = self.lock_shared()?;
let (generation, records) = manifest::current_version(&self.path, &master)?;
Ok(IndexVersion {
generation,
records,
})
}
pub fn add_if(
&mut self,
source: &Path,
name: Option<&str>,
expected: Option<IndexVersion>,
) -> Result<WriteOutcome> {
let master = self.require_unlocked()?;
let _lock = self.lock_exclusive()?;
let source = source
.canonicalize()
.map_err(|_| Error::invalid_name(source.display()))?;
if !source.is_file() && !source.is_dir() {
return Err(Error::invalid_name(source.display()));
}
let root_name = match name {
Some(n) => n.to_string(),
None => source
.file_name()
.map(|n| n.to_string_lossy().to_string())
.ok_or_else(|| Error::invalid_name(source.display()))?,
};
sanitize::validate_root_name(&root_name)?;
let (mut all, padding) = manifest::load_with_padding(&self.path, &master)?;
let (gen, records) = manifest::current_version(&self.path, &master)?;
let current = IndexVersion {
generation: gen,
records,
};
if let Some(exp) = expected {
if exp != current {
return Ok(WriteOutcome::Conflict { current });
}
}
if all.contains_key(&root_name) {
return Ok(WriteOutcome::Conflict { current });
}
if source.is_dir() {
add_directory_tree(&self.path, &master, &source, &root_name, &mut all, padding)?;
} else {
let id = new_entry_id();
let meta = EntryMetadata {
id: id.clone(),
original_name: root_name.clone(),
original_size: 0,
is_directory: false,
children: None,
content_hash: None,
};
let (_, hash, size) =
blobs::write_entry(&self.path, &master, &id, &meta, Some(&source), padding)?;
let meta = EntryMetadata {
original_size: size,
content_hash: Some(hash),
..meta
};
all.insert(root_name.clone(), meta);
}
manifest::save(&self.path, &all, &master, padding)?;
let (gen2, records2) = manifest::current_version(&self.path, &master)?;
Ok(WriteOutcome::Applied {
version: IndexVersion {
generation: gen2,
records: records2,
},
})
}
pub fn replace_if(
&mut self,
source: &Path,
name: &str,
expected: Option<IndexVersion>,
) -> Result<WriteOutcome> {
let master = self.require_unlocked()?;
let _lock = self.lock_exclusive()?;
sanitize::validate_new_name(name)?;
let source = source
.canonicalize()
.map_err(|_| Error::invalid_name(source.display()))?;
if !source.is_file() {
return Err(Error::invalid_name(source.display()));
}
let (mut all, padding) = manifest::load_with_padding(&self.path, &master)?;
let (gen, records) = manifest::current_version(&self.path, &master)?;
let current = IndexVersion {
generation: gen,
records,
};
if let Some(exp) = expected {
if exp != current {
return Ok(WriteOutcome::Conflict { current });
}
}
let existing = match all.get(name) {
Some(e) => e.clone(),
None => return Ok(WriteOutcome::Conflict { current }),
};
if existing.is_directory {
return Err(Error::Operation(
"cannot replace a directory entry; remove it first".into(),
));
}
let old_id = existing.id.clone();
let id = new_entry_id();
let meta = EntryMetadata {
id: id.clone(),
original_name: name.to_string(),
original_size: 0,
is_directory: false,
children: None,
content_hash: None,
};
let (_, hash, size) =
blobs::write_entry(&self.path, &master, &id, &meta, Some(&source), padding)?;
let meta = EntryMetadata {
original_size: size,
content_hash: Some(hash),
..meta
};
all.insert(name.to_string(), meta);
manifest::save(&self.path, &all, &master, padding)?;
let _ = blobs::remove_blob(&self.path, &master, &old_id);
let (gen2, records2) = manifest::current_version(&self.path, &master)?;
Ok(WriteOutcome::Applied {
version: IndexVersion {
generation: gen2,
records: records2,
},
})
}
pub fn set_padding(&mut self, padding: crate::padding::Padding) -> Result<()> {
padding.validate()?;
let master = self.require_unlocked()?;
let _lock = self.lock_exclusive()?;
manifest::set_padding(&self.path, &master, padding)
}
pub fn unlock(&mut self, password: &str) -> Result<()> {
if !self.exists() {
return Err(Error::VaultNotFound);
}
let _lock = self.lock_shared()?;
self.unlock_inner(password)
}
fn unlock_inner(&mut self, password: &str) -> Result<()> {
let config = self.load_config()?;
self.keystore.unlock(password, &config)
}
pub fn lock(&mut self) {
self.keystore.lock();
}
fn require_unlocked(&self) -> Result<Key> {
Ok(self.keystore.master_key()?.clone())
}
fn lock_exclusive(&self) -> Result<VaultLock> {
let lock = VaultLock::exclusive(&self.path)?;
rotation::recover(&self.path)?;
index_log::recover(&self.path)?;
Ok(lock)
}
fn lock_shared(&self) -> Result<VaultLock> {
if rotation::pending(&self.path) || index_log::compaction_pending(&self.path) {
return self.lock_exclusive();
}
VaultLock::shared(&self.path)
}
pub fn add(&mut self, source: &Path, name: Option<&str>) -> Result<()> {
let master = self.require_unlocked()?;
let _lock = self.lock_exclusive()?;
let source = source
.canonicalize()
.map_err(|_| Error::invalid_name(source.display()))?;
if !source.is_file() && !source.is_dir() {
return Err(Error::invalid_name(source.display()));
}
let root_name = match name {
Some(n) => n.to_string(),
None => source
.file_name()
.map(|n| n.to_string_lossy().to_string())
.ok_or_else(|| Error::invalid_name(source.display()))?,
};
sanitize::validate_root_name(&root_name)?;
let (mut all, padding) = manifest::load_with_padding(&self.path, &master)?;
if all.contains_key(&root_name) {
return Err(Error::EntryExists(root_name));
}
if source.is_dir() {
add_directory_tree(&self.path, &master, &source, &root_name, &mut all, padding)?;
} else {
let id = new_entry_id();
let meta = EntryMetadata {
id: id.clone(),
original_name: root_name.clone(),
original_size: 0,
is_directory: false,
children: None,
content_hash: None,
};
let (_, hash, size) =
blobs::write_entry(&self.path, &master, &id, &meta, Some(&source), padding)?;
let meta = EntryMetadata {
original_size: size,
content_hash: Some(hash),
..meta
};
all.insert(root_name.clone(), meta);
}
manifest::save(&self.path, &all, &master, padding)?;
Ok(())
}
pub fn replace(&mut self, source: &Path, name: &str) -> Result<()> {
let master = self.require_unlocked()?;
let _lock = self.lock_exclusive()?;
sanitize::validate_new_name(name)?;
let source = source
.canonicalize()
.map_err(|_| Error::invalid_name(source.display()))?;
if !source.is_file() {
return Err(Error::invalid_name(source.display()));
}
let (mut all, padding) = manifest::load_with_padding(&self.path, &master)?;
let existing = all
.get(name)
.ok_or_else(|| Error::EntryNotFound(preview(name)))?;
if existing.is_directory {
return Err(Error::Operation(
"cannot replace a directory entry; remove it first".into(),
));
}
let old_id = existing.id.clone();
let id = new_entry_id();
let meta = EntryMetadata {
id: id.clone(),
original_name: name.to_string(),
original_size: 0,
is_directory: false,
children: None,
content_hash: None,
};
let (_, hash, size) =
blobs::write_entry(&self.path, &master, &id, &meta, Some(&source), padding)?;
let meta = EntryMetadata {
original_size: size,
content_hash: Some(hash),
..meta
};
all.insert(name.to_string(), meta);
manifest::save(&self.path, &all, &master, padding)?;
let _ = blobs::remove_blob(&self.path, &master, &old_id);
Ok(())
}
pub fn rename(&mut self, from: &str, to: &str) -> Result<()> {
let master = self.require_unlocked()?;
let _lock = self.lock_exclusive()?;
sanitize::validate_root_name(from)?;
sanitize::validate_root_name(to)?;
if from == to {
return Ok(());
}
let (mut all, padding) = manifest::load_with_padding(&self.path, &master)?;
let original = all
.get(from)
.cloned()
.ok_or_else(|| Error::EntryNotFound(preview(from)))?;
if all.contains_key(to) {
return Err(Error::EntryExists(to.to_string()));
}
let old_prefix = format!("{from}/");
let new_prefix = format!("{to}/");
let mut moves = Vec::new();
if original.is_directory {
for (path, meta) in all.range(old_prefix.clone()..) {
if !path.starts_with(&old_prefix) {
break;
}
moves.push((path.clone(), meta.clone()));
}
}
moves.push((from.to_string(), original));
let old_keys: std::collections::HashSet<&str> =
moves.iter().map(|(path, _)| path.as_str()).collect();
for (path, _) in &moves {
let new_path = if path == from {
to.to_string()
} else {
format!("{new_prefix}{}", &path[old_prefix.len()..])
};
if !old_keys.contains(new_path.as_str()) && all.contains_key(&new_path) {
return Err(Error::EntryExists(new_path));
}
}
for (path, _) in &moves {
all.remove(path);
}
for (path, mut meta) in moves {
let new_path = if path == from {
to.to_string()
} else {
format!("{new_prefix}{}", &path[old_prefix.len()..])
};
meta.original_name = new_path.clone();
if let Some(children) = meta.children.as_mut() {
for child in children.iter_mut() {
if let Some(suffix) = child.strip_prefix(&old_prefix) {
*child = format!("{new_prefix}{suffix}");
} else if child == from {
*child = to.to_string();
}
}
}
all.insert(new_path, meta);
}
manifest::save(&self.path, &all, &master, padding)?;
Ok(())
}
pub fn remove(&mut self, name: &str) -> Result<()> {
let master = self.require_unlocked()?;
let _lock = self.lock_exclusive()?;
sanitize::validate_new_name(name)?;
let (mut all, padding) = manifest::load_with_padding(&self.path, &master)?;
if !all.contains_key(name) {
return Err(Error::EntryNotFound(preview(name)));
}
let removed_ids = remove_subtree(&mut all, name);
manifest::save(&self.path, &all, &master, padding)?;
for id in removed_ids {
let _ = blobs::remove_blob(&self.path, &master, &id);
}
Ok(())
}
pub fn erase(&mut self, name: &str, new_password: &str) -> Result<RotationReport> {
let old_master = self.require_unlocked()?;
let _lock = self.lock_exclusive()?;
sanitize::validate_new_name(name)?;
let (all, _padding) = manifest::load_with_padding(&self.path, &old_master)?;
if !all.contains_key(name) {
return Err(Error::EntryNotFound(preview(name)));
}
let removed = collect_subtree_names(&all, name);
let config = self.load_config()?;
let discarded = config.slot_ids().len().saturating_sub(1);
let new_master = Key::generate();
let new_config = VaultConfig::new(&new_master, new_password)?;
let report = rotation::run(
&self.path,
&old_master,
&new_master,
&new_config,
discarded,
&removed,
)?;
self.keystore.lock();
Ok(report)
}
pub fn list(&self) -> Result<Vec<EntryInfo>> {
let master = self.require_unlocked()?;
let _lock = self.lock_shared()?;
let all = manifest::load(&self.path, &master)?;
Ok(all
.iter()
.filter(|(k, _)| !k.contains('/'))
.map(|(k, m)| EntryInfo {
name: k.clone(),
size: m.original_size,
is_directory: m.is_directory,
})
.collect())
}
pub fn extract(&self, name: &str, dest: &Path) -> Result<PathBuf> {
let master = self.require_unlocked()?;
let _lock = self.lock_shared()?;
let all = manifest::load(&self.path, &master)?;
let meta = all
.get(name)
.ok_or_else(|| Error::EntryNotFound(preview(name)))?
.clone();
if !meta.is_directory {
stream_blob_to_file(&self.path, &master, &meta, dest)?;
return Ok(dest.to_path_buf());
}
crate::fsutil::create_private_dir(dest)?;
let prefix = format!("{name}/");
for (child_path, child_meta) in all.range(prefix.clone()..) {
if !child_path.starts_with(&prefix) {
break;
}
let rel = &child_path[prefix.len()..];
if rel.is_empty() {
continue;
}
let target = join_sanitized(dest, rel)?;
if child_meta.is_directory {
crate::fsutil::create_private_dir(&target)?;
} else {
stream_blob_to_file(&self.path, &master, child_meta, &target)?;
}
}
Ok(dest.to_path_buf())
}
pub fn migrate(&mut self, password: &str) -> Result<MigrationReport> {
if !self.exists() {
return Err(Error::VaultNotFound);
}
let _lock = self.lock_exclusive()?;
let config = self.load_config()?;
let master = config.unwrap_master_key(password)?;
migrate::run(&self.path, &master)
}
pub fn create_recovery_kit(&mut self, password: &str) -> Result<RecoveryCode> {
if !self.exists() {
return Err(Error::VaultNotFound);
}
let _lock = self.lock_exclusive()?;
let config = self.load_config()?;
let master = config.unwrap_master_key(password)?;
recovery::create(&self.path, &master)
}
pub fn has_recovery_kit(&self) -> bool {
recovery::exists(&self.path)
}
pub fn recover(&mut self, recovery_code: &str, new_password: &str) -> Result<()> {
if !self.path.is_dir() {
return Err(Error::VaultNotFound);
}
let _lock = self.lock_exclusive()?;
let master = recovery::unlock(&self.path, recovery_code)?;
match manifest::load(&self.path, &master) {
Ok(_) | Err(Error::MigrationRequired) => {}
Err(_) => {
return Err(Error::Operation(
"recovery kit does not unlock this vault's index".into(),
))
}
}
let config = VaultConfig::new(&master, new_password)?;
self.write_config(&config)?;
if let Err(e) = recovery::remove(&self.path) {
self.keystore.lock();
return Err(Error::Operation(format!(
"vault recovered, but the recovery kit could not be deleted; \
remove {} manually: {e}",
self.path.join("vault.recovery").display()
)));
}
self.keystore.lock();
Ok(())
}
pub fn keyslots(&self) -> Result<Vec<KeyslotInfo>> {
if !self.exists() {
return Err(Error::VaultNotFound);
}
let _lock = self.lock_shared()?;
Ok(self.load_config()?.slot_ids())
}
pub fn add_keyslot(
&mut self,
existing_password: &str,
new_password: &str,
) -> Result<KeyslotInfo> {
if !self.exists() {
return Err(Error::VaultNotFound);
}
if existing_password == new_password {
return Err(Error::Operation(
"new passphrase must differ from the authorizing passphrase".into(),
));
}
let _lock = self.lock_exclusive()?;
let config = self.load_config()?;
let (master, _) = config.unlock(existing_password)?;
let (new_config, info) = config.add_slot(&master, existing_password, new_password)?;
self.write_config(&new_config)?;
Ok(info)
}
pub fn remove_keyslot(&mut self, slot_id: &str, password: &str) -> Result<()> {
if !self.exists() {
return Err(Error::VaultNotFound);
}
let _lock = self.lock_exclusive()?;
let config = self.load_config()?;
let (_, authorizing) = config.unlock(password)?;
let target = config
.slot_index(slot_id)
.ok_or_else(|| Error::Operation(format!("no keyslot with id {slot_id:?}")))?;
if target == authorizing {
return Err(Error::Operation(
"authorize removal with a passphrase from a keyslot that will remain".into(),
));
}
let new_config = config.remove_slot(target)?;
self.write_config(&new_config)?;
Ok(())
}
pub fn change_password(&mut self, old_password: &str, new_password: &str) -> Result<()> {
if !self.exists() {
return Err(Error::VaultNotFound);
}
let _lock = self.lock_exclusive()?;
let config = self.load_config()?;
let (master, index) = config.unlock(old_password)?;
let new_config = config.rewrap_slot(index, &master, new_password)?;
self.write_config(&new_config)?;
Ok(())
}
pub fn rotate(&mut self, old_password: &str, new_password: &str) -> Result<RotationReport> {
if !self.exists() {
return Err(Error::VaultNotFound);
}
let _lock = self.lock_exclusive()?;
let config = self.load_config()?;
let (old_master, _) = config.unlock(old_password)?;
let discarded_keyslots = config.slot_ids().len().saturating_sub(1);
let new_master = Key::generate();
let new_config = VaultConfig::new(&new_master, new_password)?;
let report = rotation::run(
&self.path,
&old_master,
&new_master,
&new_config,
discarded_keyslots,
&std::collections::HashSet::new(),
)?;
self.keystore.lock();
Ok(report)
}
pub fn apply_batch(&mut self, ops: &[BatchOp]) -> Result<()> {
let master = self.require_unlocked()?;
let _lock = self.lock_exclusive()?;
let (mut all, padding) = manifest::load_with_padding(&self.path, &master)?;
let original_ids: std::collections::HashSet<String> =
all.values().map(|meta| meta.id.clone()).collect();
let mut written_ids = std::collections::HashSet::new();
for op in ops {
match op {
BatchOp::Add { source, name } => {
let source = source
.canonicalize()
.map_err(|_| Error::invalid_name(source.display()))?;
if !source.is_file() && !source.is_dir() {
return Err(Error::invalid_name(source.display()));
}
let root_name = match name {
Some(n) => n.clone(),
None => source
.file_name()
.map(|n| n.to_string_lossy().to_string())
.ok_or_else(|| Error::invalid_name(source.display()))?,
};
sanitize::validate_root_name(&root_name)?;
if all.contains_key(&root_name) {
return Err(Error::EntryExists(root_name));
}
if source.is_dir() {
let created = add_directory_tree(
&self.path, &master, &source, &root_name, &mut all, padding,
)?;
written_ids.extend(created);
} else {
let id = new_entry_id();
let meta = EntryMetadata {
id: id.clone(),
original_name: root_name.clone(),
original_size: 0,
is_directory: false,
children: None,
content_hash: None,
};
let (_, hash, size) = blobs::write_entry(
&self.path,
&master,
&id,
&meta,
Some(&source),
padding,
)?;
written_ids.insert(id);
all.insert(
root_name,
EntryMetadata {
original_size: size,
content_hash: Some(hash),
..meta
},
);
}
}
BatchOp::Replace { source, name } => {
sanitize::validate_new_name(name)?;
let source = source
.canonicalize()
.map_err(|_| Error::invalid_name(source.display()))?;
if !source.is_file() {
return Err(Error::invalid_name(source.display()));
}
let existing = all
.get(name)
.ok_or_else(|| Error::EntryNotFound(preview(name)))?
.clone();
if existing.is_directory {
return Err(Error::Operation(
"cannot replace a directory entry; remove it first".into(),
));
}
let id = new_entry_id();
let meta = EntryMetadata {
id: id.clone(),
original_name: name.clone(),
original_size: 0,
is_directory: false,
children: None,
content_hash: None,
};
let (_, hash, size) = blobs::write_entry(
&self.path,
&master,
&id,
&meta,
Some(&source),
padding,
)?;
written_ids.insert(id);
all.insert(
name.clone(),
EntryMetadata {
original_size: size,
content_hash: Some(hash),
..meta
},
);
}
BatchOp::Remove { name } => {
sanitize::validate_new_name(name)?;
if !all.contains_key(name) {
return Err(Error::EntryNotFound(preview(name)));
}
let _ = remove_subtree(&mut all, name);
}
}
}
manifest::save(&self.path, &all, &master, padding)?;
let final_ids: std::collections::HashSet<String> =
all.values().map(|meta| meta.id.clone()).collect();
for id in original_ids.into_iter().chain(written_ids) {
if !final_ids.contains(&id) {
let _ = blobs::remove_blob(&self.path, &master, &id);
}
}
Ok(())
}
pub fn verify(&mut self, password: &str) -> Result<IntegrityReport> {
if !self.exists() {
return Err(Error::VaultNotFound);
}
let _lock = self.lock_shared()?;
self.verify_with_lock(password)
}
fn verify_with_lock(&mut self, password: &str) -> Result<IntegrityReport> {
let was_unlocked = self.is_unlocked();
if !was_unlocked {
self.unlock_inner(password)?;
}
let result = self.verify_unlocked();
if !was_unlocked {
self.lock();
}
result
}
fn verify_unlocked(&mut self) -> Result<IntegrityReport> {
let master = self.require_unlocked()?;
let all = manifest::load(&self.path, &master)?;
let mut report = IntegrityReport {
total_entries: all.len(),
..IntegrityReport::default()
};
for (name, meta) in all.iter() {
match blobs::read_entry_checked(&self.path, &master, meta, |_| Ok(())) {
Ok(_) => report.verified += 1,
Err(Error::Io(ref e)) if e.kind() == std::io::ErrorKind::NotFound => {
report.missing.push(name.clone());
}
Err(_) => report.corrupted.push(name.clone()),
}
}
Ok(report)
}
pub fn prune_orphans(&mut self) -> Result<usize> {
let master = self.require_unlocked()?;
let _lock = self.lock_exclusive()?;
let data_dir = self.path.join("d");
let manifest_file = data_dir.join(".manifest.enc");
if !manifest_file.is_file() {
return Err(Error::InvalidVault);
}
let all = manifest::load(&self.path, &master)?;
let referenced: std::collections::HashSet<PathBuf> = all
.values()
.map(|meta| blobs::blob_path(&self.path, &master, &meta.id))
.collect();
let mut removed = 0usize;
for entry in walkdir::WalkDir::new(&data_dir).min_depth(1) {
let entry = entry.map_err(|_| Error::InvalidVault)?;
if !entry.file_type().is_file() {
continue;
}
let path = entry.path();
if path == manifest_file.as_path() || referenced.contains(path) {
continue;
}
let name = entry.file_name().to_string_lossy();
if !name.ends_with(".enc") && !name.contains(".tmp-") {
continue;
}
fs::remove_file(path)?;
removed += 1;
}
if let Ok(shards) = fs::read_dir(&data_dir) {
for shard in shards.flatten() {
if shard.path().is_dir() {
let _ = fs::remove_dir(shard.path());
}
}
}
Ok(removed)
}
}
impl Drop for Vault {
fn drop(&mut self) {
self.keystore.lock();
}
}
fn add_directory_tree(
vault_dir: &Path,
master: &Key,
source_root: &Path,
vault_name: &str,
all: &mut ManifestMap,
padding: crate::padding::Padding,
) -> Result<Vec<String>> {
use walkdir::WalkDir;
let entries: Vec<_> = WalkDir::new(source_root)
.sort_by_file_name()
.into_iter()
.collect::<std::result::Result<Vec<_>, _>>()
.map_err(|_| Error::invalid_name(source_root.display()))?;
let mut planned = Vec::with_capacity(entries.len());
let mut seen = std::collections::HashSet::new();
seen.insert(vault_name.to_string());
for entry in &entries {
let ft = entry.file_type();
if ft.is_symlink() || (!ft.is_dir() && !ft.is_file()) {
continue;
}
let rel = relative_entry_name(entry.path(), source_root)?;
if rel.is_empty() {
continue;
}
sanitize::validate_new_name(&rel)?;
let full = format!("{vault_name}/{rel}");
if all.contains_key(&full) || !seen.insert(full.clone()) {
return Err(Error::EntryExists(full));
}
planned.push((
full,
ft.is_dir(),
ft.is_file().then(|| entry.path().to_path_buf()),
));
}
let mut created = Vec::new();
let root_id = new_entry_id();
created.push(root_id.clone());
all.insert(
vault_name.to_string(),
EntryMetadata {
id: root_id,
original_name: vault_name.to_string(),
original_size: 0,
is_directory: true,
children: Some(Vec::new()),
content_hash: None,
},
);
let mut dir_paths: Vec<String> = vec![vault_name.to_string()];
for (full, is_dir, source) in planned {
let parent_full = full
.rsplit_once('/')
.map(|(p, _)| p.to_string())
.ok_or(Error::InvalidVault)?;
if is_dir {
let id = new_entry_id();
created.push(id.clone());
all.insert(
full.clone(),
EntryMetadata {
id,
original_name: full.clone(),
original_size: 0,
is_directory: true,
children: Some(Vec::new()),
content_hash: None,
},
);
dir_paths.push(full.clone());
} else if let Some(source) = source {
let id = new_entry_id();
let meta = EntryMetadata {
id: id.clone(),
original_name: full.clone(),
original_size: 0,
is_directory: false,
children: None,
content_hash: None,
};
let (_, hash, size) =
blobs::write_entry(vault_dir, master, &id, &meta, Some(&source), padding)?;
created.push(id);
all.insert(
full.clone(),
EntryMetadata {
original_size: size,
content_hash: Some(hash),
..meta
},
);
}
if let Some(pmeta) = all.get_mut(&parent_full) {
if let Some(children) = pmeta.children.as_mut() {
children.push(full);
}
}
}
for dir_path in &dir_paths {
let meta = all.get(dir_path).cloned().ok_or(Error::InvalidVault)?;
let (_, hash, _) = blobs::write_entry(
vault_dir,
master,
&meta.id,
&meta,
None,
crate::padding::Padding::None,
)?;
if let Some(stored) = all.get_mut(dir_path) {
stored.content_hash = Some(hash);
}
}
Ok(created)
}
fn relative_entry_name(path: &Path, root: &Path) -> Result<String> {
let rel = path
.strip_prefix(root)
.map_err(|_| Error::invalid_name(path.display()))?;
let mut parts = Vec::new();
for component in rel.components() {
match component {
std::path::Component::Normal(part) => parts.push(part.to_string_lossy()),
_ => return Err(Error::invalid_name(path.display())),
}
}
Ok(parts.join("/"))
}
fn subtree_names(all: &ManifestMap, name: &str) -> Vec<String> {
let mut seen = std::collections::HashSet::new();
let mut stack = vec![name.to_string()];
if all.get(name).is_some_and(|meta| meta.is_directory) {
let prefix = format!("{name}/");
for (path, _) in all.range(prefix.clone()..) {
if !path.starts_with(&prefix) {
break;
}
stack.push(path.clone());
}
}
while let Some(cur) = stack.pop() {
if !seen.insert(cur.clone()) {
continue;
}
if let Some(meta) = all.get(&cur) {
if let Some(children) = &meta.children {
stack.extend(children.iter().cloned());
}
}
}
seen.into_iter().collect()
}
fn remove_subtree(all: &mut ManifestMap, name: &str) -> Vec<String> {
let mut ids = Vec::new();
for entry_name in subtree_names(all, name) {
if let Some(meta) = all.remove(&entry_name) {
ids.push(meta.id);
}
}
ids
}
fn collect_subtree_names(all: &ManifestMap, name: &str) -> std::collections::HashSet<String> {
subtree_names(all, name).into_iter().collect()
}
fn join_sanitized(base: &Path, rel: &str) -> Result<PathBuf> {
sanitize::sanitize_stored_name(rel)?;
Ok(base.join(rel))
}
fn stream_blob_to_file(
vault_dir: &Path,
master: &Key,
meta: &EntryMetadata,
target: &Path,
) -> Result<()> {
let tmp = crate::fsutil::sibling_temp_path(target);
let outcome = (|| -> Result<()> {
{
let f = crate::fsutil::create_private_file(&tmp)?;
let mut w = std::io::BufWriter::new(f);
blobs::read_entry_checked(vault_dir, master, meta, |chunk| {
w.write_all(chunk)?;
Ok(())
})?;
w.flush()?;
w.get_ref().sync_all()?;
}
fs::rename(&tmp, target)?;
crate::fsutil::sync_dir(target.parent().unwrap_or_else(|| Path::new(".")));
Ok(())
})();
match outcome {
Ok(()) => Ok(()),
Err(e) => {
let _ = fs::remove_file(&tmp);
Err(e)
}
}
}
fn preview(name: &str) -> String {
name.chars().take(64).collect()
}
fn new_entry_id() -> String {
let mut bytes = [0u8; 16];
crypto::fill_random(&mut bytes);
bytes.iter().map(|b| format!("{b:02x}")).collect()
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn relative_entry_names_use_forward_slashes() {
let root = Path::new("root");
let nested = root.join("sub").join("file.txt");
assert_eq!(
relative_entry_name(&nested, root).unwrap(),
"sub/file.txt",
"manifest names must use '/' on every platform"
);
}
#[test]
fn directory_tree_preflight_rejects_nested_collisions_before_writing() {
let tmp = tempfile::tempdir().unwrap();
let vault_dir = tmp.path().join("vault");
std::fs::create_dir_all(vault_dir.join("d")).unwrap();
let master = Key::generate();
let source = tmp.path().join("tree");
std::fs::create_dir_all(source.join("sub")).unwrap();
std::fs::write(source.join("sub").join("file.txt"), b"payload").unwrap();
let mut all = ManifestMap::new();
all.insert(
"tree/sub/file.txt".to_string(),
EntryMetadata {
id: "stale".into(),
original_name: "tree/sub/file.txt".into(),
original_size: 1,
is_directory: false,
children: None,
content_hash: None,
},
);
let err = add_directory_tree(
&vault_dir,
&master,
&source,
"tree",
&mut all,
crate::padding::Padding::None,
)
.unwrap_err();
assert!(matches!(err, Error::EntryExists(_)));
assert!(std::fs::read_dir(vault_dir.join("d"))
.unwrap()
.next()
.is_none());
assert_eq!(all.len(), 1);
assert!(all.contains_key("tree/sub/file.txt"));
}
#[test]
fn shared_reads_recover_a_committed_compaction() {
let tmp = tempfile::tempdir().unwrap();
let mut vault = Vault::new(tmp.path().join("vault"));
vault.init("pw").unwrap();
let src = tmp.path().join("a.txt");
std::fs::write(&src, b"payload").unwrap();
vault.add(&src, None).unwrap();
let data = vault.path().join("d");
let snapshot = std::fs::read(data.join(".manifest.enc")).unwrap();
let log = std::fs::read(data.join(".index.log")).unwrap();
let mut generation = [0u8; 8];
generation.copy_from_slice(&log[10..18]);
crate::fsutil::atomic_write(&data.join(".index.snapshot.next"), &snapshot).unwrap();
crate::fsutil::atomic_write(&data.join(".index.log.next"), &log).unwrap();
let journal = serde_json::json!({
"version": 1,
"generation": u64::from_le_bytes(generation),
"snapshot_sha256": index_log::digest(&snapshot),
});
crate::fsutil::atomic_write(
&data.join(".index.compact"),
&serde_json::to_vec(&journal).unwrap(),
)
.unwrap();
let names: Vec<_> = vault
.list()
.unwrap()
.into_iter()
.map(|entry| entry.name)
.collect();
assert_eq!(names, vec!["a.txt"]);
assert!(!data.join(".index.compact").exists());
assert!(!data.join(".index.snapshot.next").exists());
}
}