#[allow(unused_imports)]
use crate::prelude::*;
use std::fs;
#[cfg(any(unix, windows))]
use std::fs::OpenOptions;
use std::path::{Path, PathBuf};
use chacha20poly1305::aead::{Aead, KeyInit, Payload};
use chacha20poly1305::{XChaCha20Poly1305, XNonce};
use crate::error::{OmegaError, Result};
use super::crypto::{ct_eq, hmac_sha256, pbkdf2_hmac_sha256};
const VAULT_MAGIC: &[u8; 8] = b"OMEGAVLT";
const LEGACY_VERSION: u8 = 1;
const CURRENT_VERSION: u8 = 2;
const VERSION_HEADER_LEN: usize = 8 + 1;
const XNONCE_LEN: usize = 24;
const V2_HEADER_LEN: usize = VERSION_HEADER_LEN + XNONCE_LEN;
const LEGACY_NONCE_LEN: usize = 16;
const LEGACY_HEADER_LEN: usize = VERSION_HEADER_LEN + LEGACY_NONCE_LEN;
const LEGACY_TAG_LEN: usize = 32;
const AEAD_TAG_LEN: usize = 16;
#[derive(Debug, Clone)]
pub struct Vault {
aead_key: [u8; 32],
legacy_enc_key: [u8; 32],
legacy_mac_key: [u8; 32],
}
impl Vault {
pub fn from_secret(secret: &str, salt: &[u8], iterations: u32) -> Result<Self> {
if secret.len() < 16 {
return Err(OmegaError::Config(
"vault secret must be at least 16 bytes".into(),
));
}
let master = pbkdf2_hmac_sha256(secret.as_bytes(), salt, iterations.max(10_000));
let aead_key = hmac_sha256(&master, b"omega-vault-aead-xchacha20poly1305-v2");
let legacy_enc_key = hmac_sha256(&master, b"omega-vault-enc-v1");
let legacy_mac_key = hmac_sha256(&master, b"omega-vault-mac-v1");
Ok(Self {
aead_key,
legacy_enc_key,
legacy_mac_key,
})
}
pub fn seal(&self, plaintext: &[u8]) -> Result<Vec<u8>> {
let mut nonce = [0u8; XNONCE_LEN];
getrandom::getrandom(&mut nonce).map_err(|error| {
OmegaError::Persist(format!("vault nonce generation failed: {error}"))
})?;
let mut header = Vec::with_capacity(V2_HEADER_LEN);
header.extend_from_slice(VAULT_MAGIC);
header.push(CURRENT_VERSION);
header.extend_from_slice(&nonce);
let cipher = XChaCha20Poly1305::new_from_slice(&self.aead_key)
.map_err(|_| OmegaError::Persist("invalid vault encryption key".into()))?;
let ciphertext = cipher
.encrypt(
XNonce::from_slice(&nonce),
Payload {
msg: plaintext,
aad: &header,
},
)
.map_err(|_| OmegaError::Persist("vault encryption failed".into()))?;
header.extend_from_slice(&ciphertext);
Ok(header)
}
pub fn open(&self, blob: &[u8]) -> Result<Vec<u8>> {
if blob.len() < VERSION_HEADER_LEN {
return Err(OmegaError::Persist("vault blob truncated".into()));
}
if &blob[..8] != VAULT_MAGIC {
return Err(OmegaError::Persist("invalid vault header".into()));
}
match blob[8] {
LEGACY_VERSION => self.open_legacy_v1(blob),
CURRENT_VERSION => self.open_v2(blob),
_ => Err(OmegaError::Persist("unsupported vault version".into())),
}
}
fn open_v2(&self, blob: &[u8]) -> Result<Vec<u8>> {
if blob.len() < V2_HEADER_LEN + AEAD_TAG_LEN {
return Err(OmegaError::Persist("vault blob truncated".into()));
}
let nonce = XNonce::from_slice(&blob[VERSION_HEADER_LEN..V2_HEADER_LEN]);
let cipher = XChaCha20Poly1305::new_from_slice(&self.aead_key)
.map_err(|_| OmegaError::Persist("invalid vault encryption key".into()))?;
cipher
.decrypt(
nonce,
Payload {
msg: &blob[V2_HEADER_LEN..],
aad: &blob[..V2_HEADER_LEN],
},
)
.map_err(|_| OmegaError::Persist("vault AEAD authentication failed".into()))
}
fn open_legacy_v1(&self, blob: &[u8]) -> Result<Vec<u8>> {
if blob.len() < LEGACY_HEADER_LEN + LEGACY_TAG_LEN {
return Err(OmegaError::Persist("legacy vault blob truncated".into()));
}
let split = blob.len() - LEGACY_TAG_LEN;
let (body, tag) = blob.split_at(split);
let expected_tag = hmac_sha256(&self.legacy_mac_key, body);
if !ct_eq(tag, &expected_tag) {
return Err(OmegaError::Persist(
"legacy vault MAC verification failed".into(),
));
}
let mut nonce = [0u8; LEGACY_NONCE_LEN];
nonce.copy_from_slice(&body[VERSION_HEADER_LEN..LEGACY_HEADER_LEN]);
Ok(self.legacy_keystream_xor(&nonce, &body[LEGACY_HEADER_LEN..]))
}
fn legacy_keystream_xor(&self, nonce: &[u8; LEGACY_NONCE_LEN], data: &[u8]) -> Vec<u8> {
let mut out = Vec::with_capacity(data.len());
let mut counter: u32 = 0;
for chunk in data.chunks(32) {
let mut input = [0u8; LEGACY_NONCE_LEN + 4];
input[..LEGACY_NONCE_LEN].copy_from_slice(nonce);
input[LEGACY_NONCE_LEN..].copy_from_slice(&counter.to_be_bytes());
let block = hmac_sha256(&self.legacy_enc_key, &input);
for (byte, key_byte) in chunk.iter().zip(block.iter()) {
out.push(*byte ^ *key_byte);
}
counter = counter.wrapping_add(1);
}
out
}
pub fn save_sealed(&self, path: &Path, plaintext: &[u8]) -> Result<()> {
let blob = self.seal(plaintext)?;
write_blob_atomically(path, &blob)
}
pub fn load_sealed(&self, path: &Path) -> Result<Vec<u8>> {
let blob = fs::read(path).map_err(|e| OmegaError::Persist(e.to_string()))?;
self.open(&blob)
}
}
fn write_blob_atomically(path: &Path, blob: &[u8]) -> Result<()> {
write_blob_atomically_with(path, blob, |from, to| fs::rename(from, to))
}
fn write_blob_atomically_with<F>(path: &Path, blob: &[u8], replace: F) -> Result<()>
where
F: FnOnce(&Path, &Path) -> std::io::Result<()>,
{
let parent = path
.parent()
.filter(|parent| !parent.as_os_str().is_empty())
.unwrap_or_else(|| Path::new("."));
crate::private_fs::create_dir_all(parent)
.map_err(|e| OmegaError::Persist(format!("vault directory create: {e}")))?;
let file_name = path
.file_name()
.and_then(|name| name.to_str())
.ok_or_else(|| OmegaError::Persist(format!("invalid vault path: {}", path.display())))?;
let temp_path = parent.join(format!(".{file_name}.{}.tmp", crate::new_uuid()));
let result = (|| -> Result<()> {
use std::io::Write;
let mut file = crate::private_fs::open_options()
.write(true)
.create_new(true)
.open(&temp_path)
.map_err(|e| OmegaError::Persist(format!("vault temp create: {e}")))?;
file.write_all(blob)
.and_then(|()| file.sync_all())
.map_err(|e| OmegaError::Persist(format!("vault temp write: {e}")))?;
replace(&temp_path, path)
.map_err(|e| OmegaError::Persist(format!("vault atomic replace: {e}")))?;
Ok(())
})();
if result.is_err() {
let _ = fs::remove_file(&temp_path);
}
result
}
#[derive(Debug)]
pub struct StorageLock {
#[cfg(any(unix, windows))]
_file: std::fs::File,
}
impl StorageLock {
pub fn acquire(lock_path: impl Into<PathBuf>) -> Result<Self> {
let lock_path = lock_path.into();
if let Some(parent) = lock_path
.parent()
.filter(|parent| !parent.as_os_str().is_empty())
{
fs::create_dir_all(parent).map_err(|e| OmegaError::Persist(e.to_string()))?;
}
#[cfg(any(unix, windows))]
{
use fs2::FileExt;
let file = OpenOptions::new()
.read(true)
.write(true)
.create(true)
.truncate(false)
.open(&lock_path)
.map_err(|e| OmegaError::Persist(format!("storage lock open failed: {e}")))?;
match file.try_lock_exclusive() {
Ok(()) => Ok(Self { _file: file }),
Err(error) if error.kind() == std::io::ErrorKind::WouldBlock => Err(
OmegaError::ExecutionBlocked(format!("storage lock busy: {error}")),
),
Err(error) => Err(OmegaError::Persist(format!(
"storage lock acquire failed: {error}"
))),
}
}
#[cfg(not(any(unix, windows)))]
{
let _ = lock_path;
Err(OmegaError::ExecutionBlocked(
"storage locking is unsupported on this platform".into(),
))
}
}
}
impl Drop for StorageLock {
fn drop(&mut self) {
#[cfg(any(unix, windows))]
{
let _ = fs2::FileExt::unlock(&self._file);
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::sync::atomic::{AtomicU64, Ordering};
static NEXT_TEMP_FILE: AtomicU64 = AtomicU64::new(0);
fn temp_path(label: &str) -> PathBuf {
let sequence = NEXT_TEMP_FILE.fetch_add(1, Ordering::Relaxed);
std::env::temp_dir().join(format!(
"omega-vault-{label}-{}-{sequence}.bin",
std::process::id()
))
}
#[cfg(any(unix, windows))]
struct StorageLockChild(std::process::Child);
#[cfg(any(unix, windows))]
impl Drop for StorageLockChild {
fn drop(&mut self) {
let _ = self.0.kill();
let _ = self.0.wait();
}
}
#[cfg(any(unix, windows))]
fn spawn_storage_lock_child(mode: &str, path: &Path) -> StorageLockChild {
use std::process::{Command, Stdio};
let child = Command::new(std::env::current_exe().expect("test executable path"))
.args(["storage_lock_process_child", "--nocapture"])
.env("OMEGA_STORAGE_LOCK_CHILD_MODE", mode)
.env("OMEGA_STORAGE_LOCK_PATH", path)
.stdout(Stdio::piped())
.stderr(Stdio::piped())
.spawn()
.expect("spawn storage-lock child process");
StorageLockChild(child)
}
#[cfg(any(unix, windows))]
fn wait_for_lock_child(child: &mut StorageLockChild) {
use std::io::BufRead as _;
let stdout = child.0.stdout.as_mut().expect("child stdout");
let mut reader = std::io::BufReader::new(stdout);
let mut line = String::new();
loop {
line.clear();
let bytes = reader.read_line(&mut line).expect("read child output");
assert_ne!(
bytes, 0,
"lock-holder child exited before acquiring the lock"
);
if line.contains("LOCK_HELD") {
return;
}
}
}
#[cfg(any(unix, windows))]
fn try_storage_lock_in_child(path: &Path) -> bool {
use std::process::{Command, Stdio};
let output = Command::new(std::env::current_exe().expect("test executable path"))
.args(["storage_lock_process_child", "--nocapture"])
.env("OMEGA_STORAGE_LOCK_CHILD_MODE", "try")
.env("OMEGA_STORAGE_LOCK_PATH", path)
.stdout(Stdio::piped())
.stderr(Stdio::piped())
.output()
.expect("run storage-lock contender process");
assert!(
output.status.success(),
"contender process failed: {}",
String::from_utf8_lossy(&output.stderr)
);
let stdout = String::from_utf8_lossy(&output.stdout);
if stdout.contains("LOCK_ACQUIRED") {
true
} else if stdout.contains("LOCK_BUSY") {
false
} else {
panic!("contender did not report its lock result: {stdout}");
}
}
#[cfg(any(unix, windows))]
#[test]
fn storage_lock_process_child() {
use std::io::Write as _;
let Ok(mode) = std::env::var("OMEGA_STORAGE_LOCK_CHILD_MODE") else {
return;
};
let path = std::env::var_os("OMEGA_STORAGE_LOCK_PATH")
.map(PathBuf::from)
.expect("storage-lock child path");
match mode.as_str() {
"hold" => {
let _guard = StorageLock::acquire(path).expect("child acquires lock");
println!("LOCK_HELD");
std::io::stdout().flush().expect("flush ready signal");
loop {
std::thread::sleep(std::time::Duration::from_secs(60));
}
}
"try" => match StorageLock::acquire(path) {
Ok(_guard) => println!("LOCK_ACQUIRED"),
Err(error) if error.to_string().contains("storage lock busy") => {
println!("LOCK_BUSY")
}
Err(error) => panic!("unexpected lock error: {error}"),
},
other => panic!("unknown storage-lock child mode: {other}"),
}
}
#[test]
fn vault_roundtrip_and_tamper_detection() {
let vault = Vault::from_secret("super-secret-passphrase-2026", b"omega-salt", 10_000)
.expect("vault init");
let mut blob = vault.seal(b"omega-state-payload").expect("seal");
assert_eq!(blob[8], CURRENT_VERSION);
assert_eq!(vault.open(&blob).expect("open"), b"omega-state-payload");
blob[V2_HEADER_LEN] ^= 0x01;
assert!(vault.open(&blob).is_err());
}
#[test]
fn repeated_writes_generate_distinct_nonces() {
let vault = Vault::from_secret("super-secret-passphrase-2026", b"omega-salt", 10_000)
.expect("vault init");
let first_path = temp_path("write-a");
let second_path = temp_path("write-b");
vault
.save_sealed(&first_path, b"same plaintext")
.expect("first write");
vault
.save_sealed(&second_path, b"same plaintext")
.expect("second write");
let first = fs::read(&first_path).expect("read first blob");
let second = fs::read(&second_path).expect("read second blob");
assert_ne!(
&first[VERSION_HEADER_LEN..V2_HEADER_LEN],
&second[VERSION_HEADER_LEN..V2_HEADER_LEN]
);
assert_ne!(first, second);
assert_eq!(vault.open(&first).expect("open first"), b"same plaintext");
assert_eq!(vault.open(&second).expect("open second"), b"same plaintext");
let _ = fs::remove_file(first_path);
let _ = fs::remove_file(second_path);
}
#[test]
fn failed_atomic_replace_preserves_previous_vault_blob() {
let vault = Vault::from_secret("super-secret-passphrase-2026", b"omega-salt", 10_000)
.expect("vault init");
let path = temp_path("atomic-preserve");
vault
.save_sealed(&path, b"previous encrypted state")
.expect("initial save");
let previous_blob = fs::read(&path).expect("read previous blob");
let error = write_blob_atomically_with(&path, b"replacement blob", |_, _| {
Err(std::io::Error::other("injected replace failure"))
})
.unwrap_err();
assert!(error.to_string().contains("atomic replace"), "{error}");
assert_eq!(
fs::read(&path).expect("previous blob remains"),
previous_blob
);
assert_eq!(
vault
.load_sealed(&path)
.expect("previous blob still decrypts"),
b"previous encrypted state"
);
let prefix = format!(
".{}.",
path.file_name().expect("file name").to_string_lossy()
);
assert!(
fs::read_dir(path.parent().unwrap_or_else(|| Path::new(".")))
.expect("read temp directory")
.filter_map(std::result::Result::ok)
.all(|entry| !entry.file_name().to_string_lossy().starts_with(&prefix))
);
let _ = fs::remove_file(path);
}
#[test]
fn legacy_v1_blob_can_be_read_and_migrated_by_saving_as_v2() {
let vault = Vault::from_secret("super-secret-passphrase-2026", b"omega-salt", 10_000)
.expect("vault init");
let plaintext = b"legacy omega state";
let old_blob = [
0x4f, 0x4d, 0x45, 0x47, 0x41, 0x56, 0x4c, 0x54, 0x01, 0x07, 0x07, 0x07, 0x07, 0x07,
0x07, 0x07, 0x07, 0x07, 0x07, 0x07, 0x07, 0x07, 0x07, 0x07, 0x07, 0x55, 0xe7, 0xc5,
0x7b, 0xf9, 0xa7, 0x6d, 0xcf, 0x59, 0x48, 0x49, 0xe3, 0x21, 0x93, 0x6f, 0x71, 0x10,
0xb0, 0x2c, 0xe6, 0x44, 0xf8, 0x79, 0x30, 0xf4, 0xc9, 0xad, 0x9a, 0xdf, 0x84, 0x78,
0xa3, 0x14, 0xe2, 0xf8, 0x1c, 0xe5, 0x4c, 0xeb, 0x6b, 0x21, 0x66, 0xb1, 0xe7, 0x9f,
0x4f, 0xa9, 0x1f, 0xcf, 0x62,
];
assert_eq!(old_blob[8], LEGACY_VERSION);
assert_eq!(vault.open(&old_blob).expect("open legacy"), plaintext);
let path = temp_path("migration");
fs::write(&path, old_blob).expect("write legacy blob");
let migrated_plaintext = vault.load_sealed(&path).expect("read legacy blob");
vault
.save_sealed(&path, &migrated_plaintext)
.expect("write migrated blob");
let migrated_blob = fs::read(&path).expect("read migrated blob");
assert_eq!(migrated_blob[8], CURRENT_VERSION);
assert_eq!(vault.load_sealed(&path).expect("open migrated"), plaintext);
let _ = fs::remove_file(path);
}
#[cfg(any(unix, windows))]
#[test]
fn storage_lock_excludes_live_process_and_recovers_after_termination() {
let path = temp_path("storage-lock-process");
let mut holder = spawn_storage_lock_child("hold", &path);
wait_for_lock_child(&mut holder);
let blocked_while_alive = !try_storage_lock_in_child(&path);
let kill_result = holder.0.kill();
let exit_status = holder.0.wait().expect("wait for killed lock holder");
assert!(kill_result.is_ok(), "forcefully terminate lock holder");
assert!(
!exit_status.success(),
"lock holder should not exit normally and run Rust destructors"
);
assert!(
blocked_while_alive,
"live owner must exclude another process"
);
assert!(
try_storage_lock_in_child(&path),
"a new process should acquire the lock after its former owner is killed"
);
let _ = fs::remove_file(path);
}
#[cfg(any(unix, windows))]
#[test]
fn storage_lock_prevents_concurrent_acquire() {
let path = temp_path("storage-lock");
let guard = StorageLock::acquire(&path).expect("first acquire");
assert!(StorageLock::acquire(&path).is_err());
drop(guard);
let recovered = StorageLock::acquire(&path).expect("reacquire after drop");
drop(recovered);
let _ = fs::remove_file(&path);
}
}