omega-cognitive-kernel 0.17.0

Online strategy-patch runtime: training-free RuleEffect adaptation with audit and rollback
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
#[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;

/// 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 {
    /// Creates a value from secret.
    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(
                (&nonce).into(),
                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>::try_from(&blob[VERSION_HEADER_LEN..V2_HEADER_LEN])
            .map_err(|_| OmegaError::Persist("invalid vault nonce length".into()))?;
        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
    }

    /// Saves sealed.
    pub fn save_sealed(&self, path: &Path, plaintext: &[u8]) -> Result<()> {
        let blob = self.seal(plaintext)?;
        write_blob_atomically(path, &blob)
    }

    /// Loads sealed.
    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
}

/// A cross-process advisory lock on a stable lock-file path.
///
/// Cooperating processes must lock the same path. The file is intentionally
/// retained after the guard is dropped; the operating system releases the
/// advisory lock when its handle closes or the owning process terminates.
#[derive(Debug)]
pub struct StorageLock {
    #[cfg(any(unix, windows))]
    _file: std::fs::File,
}

impl StorageLock {
    /// Performs acquire for this type.
    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");

        // 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);
    }

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