zeph-core 0.22.1

Core agent loop, configuration, context builder, metrics, and vault for Zeph
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
// SPDX-FileCopyrightText: 2026 Andrei G <bug-ops>
// SPDX-License-Identifier: MIT OR Apache-2.0

//! Concrete cryptographic backing for the durable execution layer.
//!
//! `zeph-durable` defines the durable execution *contract* as a pure Layer-0 abstraction and
//! deliberately carries no cryptographic dependency (INV-1). This module supplies the concrete
//! [`XChaCha20Poly1305Cipher`] that satisfies [`zeph_durable::PayloadCipher`]. The binary
//! constructs it from the vault-resolved `ZEPH_DURABLE_KEY` and injects it into a backend as
//! `Option<Arc<dyn PayloadCipher>>`, exactly as a database pool is handed in.
//!
//! `XChaCha20-Poly1305` is chosen for its 192-bit extended nonce: a fresh random nonce per seal
//! (INV-7) has a negligible collision probability even across the lifetime of a long-lived key, so
//! no nonce-sequencing state has to be persisted.
//!
//! # Examples
//!
//! ```
//! use zeph_core::durable::XChaCha20Poly1305Cipher;
//! use zeph_durable::{ExecutionId, StepId, PayloadCipher};
//! use zeph_durable::cipher::{EntryKindTag, PayloadAad};
//!
//! let cipher = XChaCha20Poly1305Cipher::new(0, [7u8; 32]);
//! let aad = PayloadAad::new(ExecutionId::new(), StepId::new(0), EntryKindTag::StepResult, None);
//!
//! let sealed = cipher.seal(b"tool result", &aad).unwrap();
//! assert_eq!(cipher.open(&sealed, &aad).unwrap(), b"tool result");
//! ```

use chacha20poly1305::{
    Key, KeyInit, XChaCha20Poly1305, XNonce,
    aead::{Aead, AeadCore, OsRng, Payload},
};
use zeph_durable::{CipherError, PayloadAad, PayloadCipher};
use zeroize::Zeroize;

/// `XChaCha20-Poly1305` key size, in bytes.
const KEY_LEN: usize = 32;
/// `XChaCha20` extended nonce size, in bytes.
const NONCE_LEN: usize = 24;
/// `Poly1305` authentication tag size, in bytes.
const TAG_LEN: usize = 16;
/// Length of the leading key-id selector byte.
const KEY_ID_LEN: usize = 1;
/// Offset one past the nonce, where the ciphertext begins.
const NONCE_END: usize = KEY_ID_LEN + NONCE_LEN;
/// Smallest valid sealed blob: `key_id || nonce || tag` (empty ciphertext).
const MIN_SEALED_LEN: usize = NONCE_END + TAG_LEN;

/// The key-id byte stamped on every payload sealed with the current `ZEPH_DURABLE_KEY`.
///
/// `seal` writes this as the leading byte and `open` selects the current key by it. Both the
/// agent-loop engine and the `zeph durable --reveal` CLI build the cipher with this id so a sealed
/// blob round-trips. Rotating to a fresh key bumps the id and registers the old one as the previous
/// slot ([`XChaCha20Poly1305Cipher::with_previous`]).
pub const DURABLE_KEY_ID: u8 = 0;

/// Failure constructing an [`XChaCha20Poly1305Cipher`] from raw vault bytes.
#[derive(Debug, thiserror::Error)]
#[non_exhaustive]
pub enum CipherKeyError {
    /// The vault-resolved key was not exactly 32 bytes.
    #[error("durable cipher key must be {expected} bytes, got {actual}")]
    InvalidKeyLength {
        /// The required key length in bytes (32).
        expected: usize,
        /// The length of the supplied key material.
        actual: usize,
    },
    /// The vault-resolved key string was not valid base64.
    #[error("durable cipher key is not valid base64")]
    MalformedEncoding,
}

/// One key registered with the cipher, addressed by its on-disk key-id byte.
struct KeySlot {
    key_id: u8,
    cipher: XChaCha20Poly1305,
}

impl KeySlot {
    /// Build a slot, copying the key into the AEAD state and zeroizing the transient input.
    fn new(key_id: u8, mut key: [u8; KEY_LEN]) -> Self {
        let cipher = XChaCha20Poly1305::new(Key::from_slice(&key));
        key.zeroize();
        Self { key_id, cipher }
    }
}

/// A vault-keyed `XChaCha20-Poly1305` [`PayloadCipher`] with a one-key rotation window.
///
/// The cipher holds a *current* key used for all seals, plus an optional *previous* key that
/// [`open`](PayloadCipher::open) can still select during a rotation window. The on-disk layout
/// `key_id(1) || nonce(24) || ciphertext || tag(16)` lets `open` pick the right key by its leading
/// byte; an unrecognized key-id fails closed with [`CipherError::UnknownKeyId`].
///
/// Key rotation is otherwise drain-based: see `book` vault documentation for the operational
/// policy. See [`zeph_durable::PayloadCipher`] for the full contract.
pub struct XChaCha20Poly1305Cipher {
    current: KeySlot,
    previous: Option<KeySlot>,
}

impl XChaCha20Poly1305Cipher {
    /// Construct a cipher with a single current key identified by `key_id`.
    ///
    /// The `key` array is zeroized once copied into the AEAD state.
    #[must_use]
    pub fn new(key_id: u8, key: [u8; KEY_LEN]) -> Self {
        Self {
            current: KeySlot::new(key_id, key),
            previous: None,
        }
    }

    /// Construct a cipher from vault-resolved key bytes, validating the length.
    ///
    /// # Errors
    ///
    /// Returns [`CipherKeyError::InvalidKeyLength`] when `key` is not exactly 32 bytes.
    ///
    /// # Examples
    ///
    /// ```
    /// use zeph_core::durable::XChaCha20Poly1305Cipher;
    ///
    /// assert!(XChaCha20Poly1305Cipher::from_vault_bytes(0, &[0u8; 32]).is_ok());
    /// assert!(XChaCha20Poly1305Cipher::from_vault_bytes(0, b"too short").is_err());
    /// ```
    pub fn from_vault_bytes(key_id: u8, key: &[u8]) -> Result<Self, CipherKeyError> {
        let array: [u8; KEY_LEN] =
            key.try_into()
                .map_err(|_| CipherKeyError::InvalidKeyLength {
                    expected: KEY_LEN,
                    actual: key.len(),
                })?;
        Ok(Self::new(key_id, array))
    }

    /// Construct the current cipher from the base64-encoded `ZEPH_DURABLE_KEY` vault value.
    ///
    /// This is the single decode path shared by the agent-loop engine and the `zeph durable
    /// --reveal` CLI; both use [`DURABLE_KEY_ID`] so a sealed blob round-trips. The key is generated
    /// in this same encoding by [`generate_durable_key_b64`].
    ///
    /// # Errors
    ///
    /// Returns [`CipherKeyError::MalformedEncoding`] when `b64_key` is not valid base64, or
    /// [`CipherKeyError::InvalidKeyLength`] when the decoded key is not exactly 32 bytes.
    ///
    /// # Examples
    ///
    /// ```
    /// use zeph_core::durable::{XChaCha20Poly1305Cipher, generate_durable_key_b64};
    ///
    /// let key = generate_durable_key_b64();
    /// assert!(XChaCha20Poly1305Cipher::from_vault_b64(&key).is_ok());
    /// assert!(XChaCha20Poly1305Cipher::from_vault_b64("not base64!").is_err());
    /// ```
    pub fn from_vault_b64(b64_key: &str) -> Result<Self, CipherKeyError> {
        use base64::Engine as _;
        let bytes = base64::engine::general_purpose::STANDARD
            .decode(b64_key.trim())
            .map_err(|_| CipherKeyError::MalformedEncoding)?;
        Self::from_vault_bytes(DURABLE_KEY_ID, &bytes)
    }

    /// Register a previous key for the rotation window.
    ///
    /// `open` will select this key for blobs whose leading key-id byte matches `key_id`; `seal`
    /// always uses the current key. Use this so in-flight executions sealed under the old key can
    /// still be replayed after a rotation.
    #[must_use]
    pub fn with_previous(mut self, key_id: u8, key: [u8; KEY_LEN]) -> Self {
        self.previous = Some(KeySlot::new(key_id, key));
        self
    }

    /// Select the AEAD state for a given on-disk key-id.
    fn select(&self, key_id: u8) -> Option<&XChaCha20Poly1305> {
        if key_id == self.current.key_id {
            Some(&self.current.cipher)
        } else {
            self.previous
                .as_ref()
                .filter(|slot| slot.key_id == key_id)
                .map(|slot| &slot.cipher)
        }
    }
}

/// Domain-separation context for deriving the control-entry HMAC key (INV-8) from
/// `ZEPH_DURABLE_KEY` via BLAKE3 `derive_key`.
const CONTROL_HMAC_CONTEXT: &str = "zeph-durable v1 control-entry HMAC key 2026";

/// Derive the row-level control-entry HMAC key (INV-8) from the base64-encoded `ZEPH_DURABLE_KEY`
/// vault value.
///
/// The HMAC key is not a separate vault secret: it is a BLAKE3 `derive_key` subkey of the same
/// `ZEPH_DURABLE_KEY` used for the AEAD payload cipher, domain-separated by a fixed context string
/// so the two keys are cryptographically independent even though they share one root secret —
/// the same pattern used for the promise resolver-token hash in `zeph-durable`'s `promise.rs`.
///
/// # Errors
///
/// Returns [`CipherKeyError::MalformedEncoding`] when `b64_key` is not valid base64, or
/// [`CipherKeyError::InvalidKeyLength`] when the decoded key is not exactly 32 bytes.
///
/// # Examples
///
/// ```
/// use zeph_core::durable::{derive_control_hmac_key_b64, generate_durable_key_b64};
///
/// let key = generate_durable_key_b64();
/// assert!(derive_control_hmac_key_b64(&key).is_ok());
/// assert!(derive_control_hmac_key_b64("not base64!").is_err());
/// ```
pub fn derive_control_hmac_key_b64(b64_key: &str) -> Result<[u8; KEY_LEN], CipherKeyError> {
    use base64::Engine as _;
    let bytes = base64::engine::general_purpose::STANDARD
        .decode(b64_key.trim())
        .map_err(|_| CipherKeyError::MalformedEncoding)?;
    if bytes.len() != KEY_LEN {
        return Err(CipherKeyError::InvalidKeyLength {
            expected: KEY_LEN,
            actual: bytes.len(),
        });
    }
    Ok(blake3::derive_key(CONTROL_HMAC_CONTEXT, &bytes))
}

/// Generate a fresh random 32-byte durable payload key, base64-encoded for vault storage.
///
/// Stored under `ZEPH_DURABLE_KEY` (never inline in TOML); decode it back with
/// [`XChaCha20Poly1305Cipher::from_vault_b64`]. Drawn from the OS CSPRNG.
///
/// # Examples
///
/// ```
/// use zeph_core::durable::{generate_durable_key_b64, XChaCha20Poly1305Cipher};
///
/// let key = generate_durable_key_b64();
/// assert!(XChaCha20Poly1305Cipher::from_vault_b64(&key).is_ok());
/// ```
#[must_use]
pub fn generate_durable_key_b64() -> String {
    use base64::Engine as _;
    let key = XChaCha20Poly1305::generate_key(&mut OsRng);
    base64::engine::general_purpose::STANDARD.encode(key.as_slice())
}

impl PayloadCipher for XChaCha20Poly1305Cipher {
    fn seal(&self, plaintext: &[u8], aad: &PayloadAad) -> Result<Vec<u8>, CipherError> {
        let aad_bytes = aad.canonical_bytes();
        let nonce = XChaCha20Poly1305::generate_nonce(&mut OsRng);
        let ciphertext = self
            .current
            .cipher
            .encrypt(
                &nonce,
                Payload {
                    msg: plaintext,
                    aad: &aad_bytes,
                },
            )
            .map_err(|_| CipherError::Authentication)?;

        let mut blob = Vec::with_capacity(KEY_ID_LEN + NONCE_LEN + ciphertext.len());
        blob.push(self.current.key_id);
        blob.extend_from_slice(nonce.as_slice());
        blob.extend_from_slice(&ciphertext);
        Ok(blob)
    }

    fn open(&self, sealed: &[u8], aad: &PayloadAad) -> Result<Vec<u8>, CipherError> {
        if sealed.len() < MIN_SEALED_LEN {
            return Err(CipherError::Malformed {
                context: "sealed blob shorter than key-id + nonce + tag",
            });
        }
        let key_id = sealed[0];
        let cipher = self
            .select(key_id)
            .ok_or(CipherError::UnknownKeyId { key_id })?;

        let nonce = XNonce::from_slice(&sealed[KEY_ID_LEN..NONCE_END]);
        let ciphertext = &sealed[NONCE_END..];
        let aad_bytes = aad.canonical_bytes();

        cipher
            .decrypt(
                nonce,
                Payload {
                    msg: ciphertext,
                    aad: &aad_bytes,
                },
            )
            .map_err(|_| CipherError::Authentication)
    }
}

#[cfg(test)]
mod tests {
    use std::assert_matches;
    use std::collections::HashSet;

    use zeph_durable::cipher::EntryKindTag;
    use zeph_durable::{DurableError, ExecutionId, StepId};

    use super::*;

    fn aad_for(exec: ExecutionId, step: u32) -> PayloadAad {
        PayloadAad::new(exec, StepId::new(step), EntryKindTag::StepResult, None)
    }

    #[test]
    fn seal_open_round_trip() {
        let cipher = XChaCha20Poly1305Cipher::new(0, [1u8; 32]);
        let aad = aad_for(ExecutionId::new(), 0);
        for plaintext in [
            b"".as_slice(),
            b"x",
            b"a longer journaled tool result payload",
        ] {
            let sealed = cipher.seal(plaintext, &aad).unwrap();
            assert_eq!(cipher.open(&sealed, &aad).unwrap(), plaintext);
        }
    }

    #[test]
    fn sealed_blob_uses_key_id_nonce_tag_layout() {
        let cipher = XChaCha20Poly1305Cipher::new(3, [2u8; 32]);
        let aad = aad_for(ExecutionId::new(), 0);
        let sealed = cipher.seal(b"", &aad).unwrap();
        // key-id byte, then 24-byte nonce, then a 16-byte tag for empty plaintext.
        assert_eq!(sealed.len(), KEY_ID_LEN + NONCE_LEN + TAG_LEN);
        assert_eq!(sealed[0], 3, "leading byte is the current key-id");
    }

    #[test]
    fn nonce_is_fresh_per_seal() {
        let cipher = XChaCha20Poly1305Cipher::new(0, [9u8; 32]);
        let aad = aad_for(ExecutionId::new(), 0);
        let a = cipher.seal(b"same", &aad).unwrap();
        let b = cipher.seal(b"same", &aad).unwrap();
        // Identical plaintext + identical AAD must still yield distinct nonces (and ciphertext).
        assert_ne!(a[KEY_ID_LEN..NONCE_END], b[KEY_ID_LEN..NONCE_END]);
        assert_ne!(a, b);
    }

    // NFR-DE-06: a CSPRNG nonce of 192 bits must not repeat across 10^6 seals.
    #[test]
    #[ignore = "slow: 1M seal iterations — run explicitly or in integration suite"]
    fn one_million_seals_produce_distinct_nonces() {
        const SEALS: usize = 1_000_000;
        let cipher = XChaCha20Poly1305Cipher::new(0, [4u8; 32]);
        let aad = aad_for(ExecutionId::new(), 0);
        let mut nonces: HashSet<[u8; NONCE_LEN]> = HashSet::with_capacity(SEALS);
        for _ in 0..SEALS {
            let sealed = cipher.seal(b"", &aad).unwrap();
            let mut nonce = [0u8; NONCE_LEN];
            nonce.copy_from_slice(&sealed[KEY_ID_LEN..NONCE_END]);
            assert!(nonces.insert(nonce), "nonce reuse detected");
        }
        assert_eq!(nonces.len(), SEALS);
    }

    #[test]
    fn open_under_different_step_fails_replay_integrity() {
        let cipher = XChaCha20Poly1305Cipher::new(0, [5u8; 32]);
        let exec = ExecutionId::new();
        let sealed = cipher.seal(b"result", &aad_for(exec, 7)).unwrap();

        let err = cipher.open(&sealed, &aad_for(exec, 8)).unwrap_err();
        assert_matches!(err, CipherError::Authentication);
        assert_matches!(DurableError::from(err), DurableError::ReplayIntegrity);
    }

    #[test]
    fn open_under_different_execution_fails_replay_integrity() {
        let cipher = XChaCha20Poly1305Cipher::new(0, [6u8; 32]);
        let sealed = cipher
            .seal(b"result", &aad_for(ExecutionId::new(), 0))
            .unwrap();

        let err = cipher
            .open(&sealed, &aad_for(ExecutionId::new(), 0))
            .unwrap_err();
        assert_matches!(DurableError::from(err), DurableError::ReplayIntegrity);
    }

    #[test]
    fn tampered_ciphertext_fails_authentication() {
        let cipher = XChaCha20Poly1305Cipher::new(0, [7u8; 32]);
        let aad = aad_for(ExecutionId::new(), 0);
        let mut sealed = cipher.seal(b"result", &aad).unwrap();
        let last = sealed.len() - 1;
        sealed[last] ^= 0xFF;
        assert_matches!(
            cipher.open(&sealed, &aad).unwrap_err(),
            CipherError::Authentication
        );
    }

    #[test]
    fn short_blob_is_malformed() {
        let cipher = XChaCha20Poly1305Cipher::new(0, [0u8; 32]);
        let aad = aad_for(ExecutionId::new(), 0);
        let err = cipher.open(&[0u8; MIN_SEALED_LEN - 1], &aad).unwrap_err();
        assert_matches!(err, CipherError::Malformed { .. });
        assert_matches!(DurableError::from(err), DurableError::Decode { .. });
    }

    #[test]
    fn unknown_key_id_fails_closed() {
        let cipher = XChaCha20Poly1305Cipher::new(0, [1u8; 32]);
        let aad = aad_for(ExecutionId::new(), 0);
        let mut sealed = cipher.seal(b"x", &aad).unwrap();
        sealed[0] = 200; // no key registered under id 200
        assert_matches!(
            cipher.open(&sealed, &aad).unwrap_err(),
            CipherError::UnknownKeyId { key_id: 200 }
        );
    }

    #[test]
    fn previous_key_opens_during_rotation_window() {
        // Seal under the old key (id 0), then rotate: current is id 1, previous is id 0.
        let old = XChaCha20Poly1305Cipher::new(0, [1u8; 32]);
        let aad = aad_for(ExecutionId::new(), 0);
        let sealed = old.seal(b"in-flight", &aad).unwrap();

        let rotated = XChaCha20Poly1305Cipher::new(1, [2u8; 32]).with_previous(0, [1u8; 32]);
        // The old blob still opens via the previous key...
        assert_eq!(rotated.open(&sealed, &aad).unwrap(), b"in-flight");
        // ...while new seals use the current key-id.
        assert_eq!(rotated.seal(b"new", &aad).unwrap()[0], 1);
    }

    #[test]
    fn from_vault_bytes_validates_length() {
        assert!(XChaCha20Poly1305Cipher::from_vault_bytes(0, &[0u8; 32]).is_ok());
        // The cipher deliberately does not implement `Debug` (it holds key material), so match on
        // the `Result` directly rather than calling `unwrap_err`.
        assert!(matches!(
            XChaCha20Poly1305Cipher::from_vault_bytes(0, b"short"),
            Err(CipherKeyError::InvalidKeyLength {
                expected: 32,
                actual: 5
            })
        ));
    }

    #[test]
    fn control_hmac_key_derives_deterministically_and_independently_of_the_aead_key() {
        use base64::Engine as _;

        let vault_key = generate_durable_key_b64();
        let hmac_key = derive_control_hmac_key_b64(&vault_key).unwrap();

        // Deterministic: the same vault value always derives the same subkey.
        assert_eq!(derive_control_hmac_key_b64(&vault_key).unwrap(), hmac_key);

        // Cryptographically independent of the raw AEAD key material (domain separation via a
        // fixed `derive_key` context distinct from the AEAD cipher's own use of the raw bytes).
        let raw_aead_key = base64::engine::general_purpose::STANDARD
            .decode(vault_key.trim())
            .unwrap();
        assert_ne!(hmac_key.as_slice(), raw_aead_key.as_slice());
    }

    #[test]
    fn control_hmac_key_rejects_malformed_or_mislength_input() {
        use base64::Engine as _;

        assert!(matches!(
            derive_control_hmac_key_b64("not base64!"),
            Err(CipherKeyError::MalformedEncoding)
        ));
        let short = base64::engine::general_purpose::STANDARD.encode(b"too short");
        assert!(matches!(
            derive_control_hmac_key_b64(&short),
            Err(CipherKeyError::InvalidKeyLength {
                expected: 32,
                actual: 9
            })
        ));
    }
}