1#[allow(unused_imports)]
2use crate::prelude::*;
3
4use std::fs;
5#[cfg(any(unix, windows))]
6use std::fs::OpenOptions;
7use std::path::{Path, PathBuf};
8
9use chacha20poly1305::aead::{Aead, KeyInit, Payload};
10use chacha20poly1305::{XChaCha20Poly1305, XNonce};
11
12use crate::error::{OmegaError, Result};
13
14use super::crypto::{ct_eq, hmac_sha256, pbkdf2_hmac_sha256};
15
16const VAULT_MAGIC: &[u8; 8] = b"OMEGAVLT";
17const LEGACY_VERSION: u8 = 1;
18const CURRENT_VERSION: u8 = 2;
19const VERSION_HEADER_LEN: usize = 8 + 1;
20const XNONCE_LEN: usize = 24;
21const V2_HEADER_LEN: usize = VERSION_HEADER_LEN + XNONCE_LEN;
22const LEGACY_NONCE_LEN: usize = 16;
23const LEGACY_HEADER_LEN: usize = VERSION_HEADER_LEN + LEGACY_NONCE_LEN;
24const LEGACY_TAG_LEN: usize = 32;
25const AEAD_TAG_LEN: usize = 16;
26
27#[derive(Debug, Clone)]
32pub struct Vault {
33 aead_key: [u8; 32],
34 legacy_enc_key: [u8; 32],
36 legacy_mac_key: [u8; 32],
37}
38
39impl Vault {
40 pub fn from_secret(secret: &str, salt: &[u8], iterations: u32) -> Result<Self> {
42 if secret.len() < 16 {
43 return Err(OmegaError::Config(
44 "vault secret must be at least 16 bytes".into(),
45 ));
46 }
47 let master = pbkdf2_hmac_sha256(secret.as_bytes(), salt, iterations.max(10_000));
48 let aead_key = hmac_sha256(&master, b"omega-vault-aead-xchacha20poly1305-v2");
49 let legacy_enc_key = hmac_sha256(&master, b"omega-vault-enc-v1");
50 let legacy_mac_key = hmac_sha256(&master, b"omega-vault-mac-v1");
51 Ok(Self {
52 aead_key,
53 legacy_enc_key,
54 legacy_mac_key,
55 })
56 }
57
58 pub fn seal(&self, plaintext: &[u8]) -> Result<Vec<u8>> {
62 let mut nonce = [0u8; XNONCE_LEN];
63 getrandom::getrandom(&mut nonce).map_err(|error| {
64 OmegaError::Persist(format!("vault nonce generation failed: {error}"))
65 })?;
66
67 let mut header = Vec::with_capacity(V2_HEADER_LEN);
68 header.extend_from_slice(VAULT_MAGIC);
69 header.push(CURRENT_VERSION);
70 header.extend_from_slice(&nonce);
71
72 let cipher = XChaCha20Poly1305::new_from_slice(&self.aead_key)
73 .map_err(|_| OmegaError::Persist("invalid vault encryption key".into()))?;
74 let ciphertext = cipher
75 .encrypt(
76 (&nonce).into(),
77 Payload {
78 msg: plaintext,
79 aad: &header,
80 },
81 )
82 .map_err(|_| OmegaError::Persist("vault encryption failed".into()))?;
83
84 header.extend_from_slice(&ciphertext);
85 Ok(header)
86 }
87
88 pub fn open(&self, blob: &[u8]) -> Result<Vec<u8>> {
93 if blob.len() < VERSION_HEADER_LEN {
94 return Err(OmegaError::Persist("vault blob truncated".into()));
95 }
96 if &blob[..8] != VAULT_MAGIC {
97 return Err(OmegaError::Persist("invalid vault header".into()));
98 }
99
100 match blob[8] {
101 LEGACY_VERSION => self.open_legacy_v1(blob),
102 CURRENT_VERSION => self.open_v2(blob),
103 _ => Err(OmegaError::Persist("unsupported vault version".into())),
104 }
105 }
106
107 fn open_v2(&self, blob: &[u8]) -> Result<Vec<u8>> {
108 if blob.len() < V2_HEADER_LEN + AEAD_TAG_LEN {
109 return Err(OmegaError::Persist("vault blob truncated".into()));
110 }
111 let nonce = <&XNonce>::try_from(&blob[VERSION_HEADER_LEN..V2_HEADER_LEN])
112 .map_err(|_| OmegaError::Persist("invalid vault nonce length".into()))?;
113 let cipher = XChaCha20Poly1305::new_from_slice(&self.aead_key)
114 .map_err(|_| OmegaError::Persist("invalid vault encryption key".into()))?;
115 cipher
116 .decrypt(
117 nonce,
118 Payload {
119 msg: &blob[V2_HEADER_LEN..],
120 aad: &blob[..V2_HEADER_LEN],
121 },
122 )
123 .map_err(|_| OmegaError::Persist("vault AEAD authentication failed".into()))
124 }
125
126 fn open_legacy_v1(&self, blob: &[u8]) -> Result<Vec<u8>> {
127 if blob.len() < LEGACY_HEADER_LEN + LEGACY_TAG_LEN {
128 return Err(OmegaError::Persist("legacy vault blob truncated".into()));
129 }
130 let split = blob.len() - LEGACY_TAG_LEN;
131 let (body, tag) = blob.split_at(split);
132 let expected_tag = hmac_sha256(&self.legacy_mac_key, body);
133 if !ct_eq(tag, &expected_tag) {
134 return Err(OmegaError::Persist(
135 "legacy vault MAC verification failed".into(),
136 ));
137 }
138
139 let mut nonce = [0u8; LEGACY_NONCE_LEN];
140 nonce.copy_from_slice(&body[VERSION_HEADER_LEN..LEGACY_HEADER_LEN]);
141 Ok(self.legacy_keystream_xor(&nonce, &body[LEGACY_HEADER_LEN..]))
142 }
143
144 fn legacy_keystream_xor(&self, nonce: &[u8; LEGACY_NONCE_LEN], data: &[u8]) -> Vec<u8> {
147 let mut out = Vec::with_capacity(data.len());
148 let mut counter: u32 = 0;
149 for chunk in data.chunks(32) {
150 let mut input = [0u8; LEGACY_NONCE_LEN + 4];
151 input[..LEGACY_NONCE_LEN].copy_from_slice(nonce);
152 input[LEGACY_NONCE_LEN..].copy_from_slice(&counter.to_be_bytes());
153 let block = hmac_sha256(&self.legacy_enc_key, &input);
154 for (byte, key_byte) in chunk.iter().zip(block.iter()) {
155 out.push(*byte ^ *key_byte);
156 }
157 counter = counter.wrapping_add(1);
158 }
159 out
160 }
161
162 pub fn save_sealed(&self, path: &Path, plaintext: &[u8]) -> Result<()> {
164 let blob = self.seal(plaintext)?;
165 write_blob_atomically(path, &blob)
166 }
167
168 pub fn load_sealed(&self, path: &Path) -> Result<Vec<u8>> {
170 let blob = fs::read(path).map_err(|e| OmegaError::Persist(e.to_string()))?;
171 self.open(&blob)
172 }
173}
174
175fn write_blob_atomically(path: &Path, blob: &[u8]) -> Result<()> {
176 write_blob_atomically_with(path, blob, |from, to| fs::rename(from, to))
177}
178
179fn write_blob_atomically_with<F>(path: &Path, blob: &[u8], replace: F) -> Result<()>
180where
181 F: FnOnce(&Path, &Path) -> std::io::Result<()>,
182{
183 let parent = path
184 .parent()
185 .filter(|parent| !parent.as_os_str().is_empty())
186 .unwrap_or_else(|| Path::new("."));
187 crate::private_fs::create_dir_all(parent)
188 .map_err(|e| OmegaError::Persist(format!("vault directory create: {e}")))?;
189 let file_name = path
190 .file_name()
191 .and_then(|name| name.to_str())
192 .ok_or_else(|| OmegaError::Persist(format!("invalid vault path: {}", path.display())))?;
193 let temp_path = parent.join(format!(".{file_name}.{}.tmp", crate::new_uuid()));
194
195 let result = (|| -> Result<()> {
196 use std::io::Write;
197 let mut file = crate::private_fs::open_options()
198 .write(true)
199 .create_new(true)
200 .open(&temp_path)
201 .map_err(|e| OmegaError::Persist(format!("vault temp create: {e}")))?;
202 file.write_all(blob)
203 .and_then(|()| file.sync_all())
204 .map_err(|e| OmegaError::Persist(format!("vault temp write: {e}")))?;
205 replace(&temp_path, path)
206 .map_err(|e| OmegaError::Persist(format!("vault atomic replace: {e}")))?;
207 Ok(())
208 })();
209 if result.is_err() {
210 let _ = fs::remove_file(&temp_path);
211 }
212 result
213}
214
215#[derive(Debug)]
221pub struct StorageLock {
222 #[cfg(any(unix, windows))]
223 _file: std::fs::File,
224}
225
226impl StorageLock {
227 pub fn acquire(lock_path: impl Into<PathBuf>) -> Result<Self> {
229 let lock_path = lock_path.into();
230 if let Some(parent) = lock_path
231 .parent()
232 .filter(|parent| !parent.as_os_str().is_empty())
233 {
234 fs::create_dir_all(parent).map_err(|e| OmegaError::Persist(e.to_string()))?;
235 }
236
237 #[cfg(any(unix, windows))]
238 {
239 use fs2::FileExt;
240
241 let file = OpenOptions::new()
242 .read(true)
243 .write(true)
244 .create(true)
245 .truncate(false)
246 .open(&lock_path)
247 .map_err(|e| OmegaError::Persist(format!("storage lock open failed: {e}")))?;
248 match file.try_lock_exclusive() {
249 Ok(()) => Ok(Self { _file: file }),
250 Err(error) if error.kind() == std::io::ErrorKind::WouldBlock => Err(
251 OmegaError::ExecutionBlocked(format!("storage lock busy: {error}")),
252 ),
253 Err(error) => Err(OmegaError::Persist(format!(
254 "storage lock acquire failed: {error}"
255 ))),
256 }
257 }
258
259 #[cfg(not(any(unix, windows)))]
260 {
261 let _ = lock_path;
262 Err(OmegaError::ExecutionBlocked(
263 "storage locking is unsupported on this platform".into(),
264 ))
265 }
266 }
267}
268
269impl Drop for StorageLock {
270 fn drop(&mut self) {
271 #[cfg(any(unix, windows))]
272 {
273 let _ = fs2::FileExt::unlock(&self._file);
274 }
275 }
276}
277
278#[cfg(test)]
279mod tests {
280 use super::*;
281 use std::sync::atomic::{AtomicU64, Ordering};
282
283 static NEXT_TEMP_FILE: AtomicU64 = AtomicU64::new(0);
284
285 fn temp_path(label: &str) -> PathBuf {
286 let sequence = NEXT_TEMP_FILE.fetch_add(1, Ordering::Relaxed);
287 std::env::temp_dir().join(format!(
288 "omega-vault-{label}-{}-{sequence}.bin",
289 std::process::id()
290 ))
291 }
292
293 #[cfg(any(unix, windows))]
294 struct StorageLockChild(std::process::Child);
295
296 #[cfg(any(unix, windows))]
297 impl Drop for StorageLockChild {
298 fn drop(&mut self) {
299 let _ = self.0.kill();
300 let _ = self.0.wait();
301 }
302 }
303
304 #[cfg(any(unix, windows))]
305 fn spawn_storage_lock_child(mode: &str, path: &Path) -> StorageLockChild {
306 use std::process::{Command, Stdio};
307
308 let child = Command::new(std::env::current_exe().expect("test executable path"))
309 .args(["storage_lock_process_child", "--nocapture"])
310 .env("OMEGA_STORAGE_LOCK_CHILD_MODE", mode)
311 .env("OMEGA_STORAGE_LOCK_PATH", path)
312 .stdout(Stdio::piped())
313 .stderr(Stdio::piped())
314 .spawn()
315 .expect("spawn storage-lock child process");
316 StorageLockChild(child)
317 }
318
319 #[cfg(any(unix, windows))]
320 fn wait_for_lock_child(child: &mut StorageLockChild) {
321 use std::io::BufRead as _;
322
323 let stdout = child.0.stdout.as_mut().expect("child stdout");
324 let mut reader = std::io::BufReader::new(stdout);
325 let mut line = String::new();
326 loop {
327 line.clear();
328 let bytes = reader.read_line(&mut line).expect("read child output");
329 assert_ne!(
330 bytes, 0,
331 "lock-holder child exited before acquiring the lock"
332 );
333 if line.contains("LOCK_HELD") {
334 return;
335 }
336 }
337 }
338
339 #[cfg(any(unix, windows))]
340 fn try_storage_lock_in_child(path: &Path) -> bool {
341 use std::process::{Command, Stdio};
342
343 let output = Command::new(std::env::current_exe().expect("test executable path"))
344 .args(["storage_lock_process_child", "--nocapture"])
345 .env("OMEGA_STORAGE_LOCK_CHILD_MODE", "try")
346 .env("OMEGA_STORAGE_LOCK_PATH", path)
347 .stdout(Stdio::piped())
348 .stderr(Stdio::piped())
349 .output()
350 .expect("run storage-lock contender process");
351 assert!(
352 output.status.success(),
353 "contender process failed: {}",
354 String::from_utf8_lossy(&output.stderr)
355 );
356 let stdout = String::from_utf8_lossy(&output.stdout);
357 if stdout.contains("LOCK_ACQUIRED") {
358 true
359 } else if stdout.contains("LOCK_BUSY") {
360 false
361 } else {
362 panic!("contender did not report its lock result: {stdout}");
363 }
364 }
365
366 #[cfg(any(unix, windows))]
367 #[test]
368 fn storage_lock_process_child() {
369 use std::io::Write as _;
370
371 let Ok(mode) = std::env::var("OMEGA_STORAGE_LOCK_CHILD_MODE") else {
372 return;
373 };
374 let path = std::env::var_os("OMEGA_STORAGE_LOCK_PATH")
375 .map(PathBuf::from)
376 .expect("storage-lock child path");
377 match mode.as_str() {
378 "hold" => {
379 let _guard = StorageLock::acquire(path).expect("child acquires lock");
380 println!("LOCK_HELD");
381 std::io::stdout().flush().expect("flush ready signal");
382 loop {
383 std::thread::sleep(std::time::Duration::from_secs(60));
384 }
385 }
386 "try" => match StorageLock::acquire(path) {
387 Ok(_guard) => println!("LOCK_ACQUIRED"),
388 Err(error) if error.to_string().contains("storage lock busy") => {
389 println!("LOCK_BUSY")
390 }
391 Err(error) => panic!("unexpected lock error: {error}"),
392 },
393 other => panic!("unknown storage-lock child mode: {other}"),
394 }
395 }
396
397 #[test]
398 fn vault_roundtrip_and_tamper_detection() {
399 let vault = Vault::from_secret("super-secret-passphrase-2026", b"omega-salt", 10_000)
400 .expect("vault init");
401 let mut blob = vault.seal(b"omega-state-payload").expect("seal");
402 assert_eq!(blob[8], CURRENT_VERSION);
403 assert_eq!(vault.open(&blob).expect("open"), b"omega-state-payload");
404
405 blob[V2_HEADER_LEN] ^= 0x01;
407 assert!(vault.open(&blob).is_err());
408 }
409
410 #[test]
411 fn repeated_writes_generate_distinct_nonces() {
412 let vault = Vault::from_secret("super-secret-passphrase-2026", b"omega-salt", 10_000)
413 .expect("vault init");
414 let first_path = temp_path("write-a");
415 let second_path = temp_path("write-b");
416
417 vault
418 .save_sealed(&first_path, b"same plaintext")
419 .expect("first write");
420 vault
421 .save_sealed(&second_path, b"same plaintext")
422 .expect("second write");
423 let first = fs::read(&first_path).expect("read first blob");
424 let second = fs::read(&second_path).expect("read second blob");
425
426 assert_ne!(
427 &first[VERSION_HEADER_LEN..V2_HEADER_LEN],
428 &second[VERSION_HEADER_LEN..V2_HEADER_LEN]
429 );
430 assert_ne!(first, second);
431 assert_eq!(vault.open(&first).expect("open first"), b"same plaintext");
432 assert_eq!(vault.open(&second).expect("open second"), b"same plaintext");
433
434 let _ = fs::remove_file(first_path);
435 let _ = fs::remove_file(second_path);
436 }
437
438 #[test]
439 fn failed_atomic_replace_preserves_previous_vault_blob() {
440 let vault = Vault::from_secret("super-secret-passphrase-2026", b"omega-salt", 10_000)
441 .expect("vault init");
442 let path = temp_path("atomic-preserve");
443 vault
444 .save_sealed(&path, b"previous encrypted state")
445 .expect("initial save");
446 let previous_blob = fs::read(&path).expect("read previous blob");
447
448 let error = write_blob_atomically_with(&path, b"replacement blob", |_, _| {
449 Err(std::io::Error::other("injected replace failure"))
450 })
451 .unwrap_err();
452
453 assert!(error.to_string().contains("atomic replace"), "{error}");
454 assert_eq!(
455 fs::read(&path).expect("previous blob remains"),
456 previous_blob
457 );
458 assert_eq!(
459 vault
460 .load_sealed(&path)
461 .expect("previous blob still decrypts"),
462 b"previous encrypted state"
463 );
464 let prefix = format!(
465 ".{}.",
466 path.file_name().expect("file name").to_string_lossy()
467 );
468 assert!(
469 fs::read_dir(path.parent().unwrap_or_else(|| Path::new(".")))
470 .expect("read temp directory")
471 .filter_map(std::result::Result::ok)
472 .all(|entry| !entry.file_name().to_string_lossy().starts_with(&prefix))
473 );
474 let _ = fs::remove_file(path);
475 }
476
477 #[test]
478 fn legacy_v1_blob_can_be_read_and_migrated_by_saving_as_v2() {
479 let vault = Vault::from_secret("super-secret-passphrase-2026", b"omega-salt", 10_000)
480 .expect("vault init");
481 let plaintext = b"legacy omega state";
482 let old_blob = [
484 0x4f, 0x4d, 0x45, 0x47, 0x41, 0x56, 0x4c, 0x54, 0x01, 0x07, 0x07, 0x07, 0x07, 0x07,
485 0x07, 0x07, 0x07, 0x07, 0x07, 0x07, 0x07, 0x07, 0x07, 0x07, 0x07, 0x55, 0xe7, 0xc5,
486 0x7b, 0xf9, 0xa7, 0x6d, 0xcf, 0x59, 0x48, 0x49, 0xe3, 0x21, 0x93, 0x6f, 0x71, 0x10,
487 0xb0, 0x2c, 0xe6, 0x44, 0xf8, 0x79, 0x30, 0xf4, 0xc9, 0xad, 0x9a, 0xdf, 0x84, 0x78,
488 0xa3, 0x14, 0xe2, 0xf8, 0x1c, 0xe5, 0x4c, 0xeb, 0x6b, 0x21, 0x66, 0xb1, 0xe7, 0x9f,
489 0x4f, 0xa9, 0x1f, 0xcf, 0x62,
490 ];
491 assert_eq!(old_blob[8], LEGACY_VERSION);
492 assert_eq!(vault.open(&old_blob).expect("open legacy"), plaintext);
493
494 let path = temp_path("migration");
495 fs::write(&path, old_blob).expect("write legacy blob");
496 let migrated_plaintext = vault.load_sealed(&path).expect("read legacy blob");
497 vault
498 .save_sealed(&path, &migrated_plaintext)
499 .expect("write migrated blob");
500 let migrated_blob = fs::read(&path).expect("read migrated blob");
501 assert_eq!(migrated_blob[8], CURRENT_VERSION);
502 assert_eq!(vault.load_sealed(&path).expect("open migrated"), plaintext);
503 let _ = fs::remove_file(path);
504 }
505
506 #[cfg(any(unix, windows))]
507 #[test]
508 fn storage_lock_excludes_live_process_and_recovers_after_termination() {
509 let path = temp_path("storage-lock-process");
510 let mut holder = spawn_storage_lock_child("hold", &path);
511 wait_for_lock_child(&mut holder);
512
513 let blocked_while_alive = !try_storage_lock_in_child(&path);
514 let kill_result = holder.0.kill();
515 let exit_status = holder.0.wait().expect("wait for killed lock holder");
516
517 assert!(kill_result.is_ok(), "forcefully terminate lock holder");
518 assert!(
519 !exit_status.success(),
520 "lock holder should not exit normally and run Rust destructors"
521 );
522 assert!(
523 blocked_while_alive,
524 "live owner must exclude another process"
525 );
526 assert!(
527 try_storage_lock_in_child(&path),
528 "a new process should acquire the lock after its former owner is killed"
529 );
530 let _ = fs::remove_file(path);
531 }
532
533 #[cfg(any(unix, windows))]
534 #[test]
535 fn storage_lock_prevents_concurrent_acquire() {
536 let path = temp_path("storage-lock");
537
538 let guard = StorageLock::acquire(&path).expect("first acquire");
539 assert!(StorageLock::acquire(&path).is_err());
540 drop(guard);
541 let recovered = StorageLock::acquire(&path).expect("reacquire after drop");
542 drop(recovered);
543 let _ = fs::remove_file(&path);
544 }
545}