omega-cognitive-kernel 0.6.1

Online strategy-patch runtime: training-free RuleEffect adaptation with audit and rollback
Documentation
#[allow(unused_imports)]
use crate::prelude::*;

use std::fs::{self, 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;

/// Authenticated encrypted storage for Vault payloads.
///
/// New blobs use XChaCha20-Poly1305 (format version 2) with a random nonce
/// generated internally. Version-1 blobs are accepted for read-only migration.
#[derive(Debug, Clone)]
pub struct Vault {
    aead_key: [u8; 32],
    // These keys are retained only to decrypt authenticated version-1 blobs.
    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,
        })
    }

    /// Encrypts plaintext and returns a version-2 blob containing its nonce.
    /// The nonce is generated by the operating system CSPRNG and is never
    /// supplied by the caller.
    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)
    }

    /// Opens a version-2 blob or a legacy version-1 blob.
    ///
    /// Version 1 is read-only compatibility support for migration. All calls to
    /// `seal` and `save_sealed` produce version 2.
    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..]))
    }

    // Kept only for decrypting authenticated v1 blobs. New encryption must use
    // the AEAD implementation above.
    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 {
    lock_path: PathBuf,
}

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() {
            fs::create_dir_all(parent).map_err(|e| OmegaError::Persist(e.to_string()))?;
        }
        OpenOptions::new()
            .write(true)
            .create_new(true)
            .open(&lock_path)
            .map_err(|e| OmegaError::ExecutionBlocked(format!("storage lock busy: {e}")))?;
        Ok(Self { lock_path })
    }
}

impl Drop for StorageLock {
    fn drop(&mut self) {
        let _ = fs::remove_file(&self.lock_path);
    }
}

#[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()
        ))
    }

    #[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");

        // The first byte after the v2 header is ciphertext, not metadata.
        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";
        // Fixed v1 fixture generated by the pre-AEAD Vault format.
        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);
    }

    #[test]
    fn storage_lock_prevents_concurrent_acquire() {
        let mut path = std::env::temp_dir();
        path.push("omega-kernel-test-storage.lock");
        let _ = fs::remove_file(&path);

        let guard = StorageLock::acquire(&path).expect("first acquire");
        assert!(StorageLock::acquire(&path).is_err());
        drop(guard);
        assert!(StorageLock::acquire(&path).is_ok());
        let _ = fs::remove_file(&path);
    }
}