Skip to main content

qualia_core_db/crypto/
sanctuary_audit.rs

1//! Sanctuary audit primitives (vault v2, first slice) — the crypto under the decoy-mirroring design.
2//!
3//! Three isolated, independently-tested primitives. Nothing here touches the vault yet; the vault
4//! wiring is a later slice. See `docs/plans/adr-sanctuary-vault-v2-cbor-decoy-mirroring.md`.
5//!
6//! 1. **Blind write-only audit channel** — an **X25519 sealed box** (anonymous ECIES): a decoy
7//!    session, holding only the audit *public* key, can [`seal_to`] a record so that only the holder
8//!    of the audit *secret* (the real lane) can [`open_sealed`] it. The writer cannot read back what
9//!    it wrote, and cannot forge or tamper without detection. This is how a coercer's actions get
10//!    logged into a channel they can append to but never read.
11//! 2. **One-way key wrapping** — [`wrap_key`]/[`unwrap_key`]: the real lane key wraps the decoy lane
12//!    key (and the audit secret), so a real session can reach *down* into the decoy to curate it,
13//!    but the decoy can never reach *up*.
14//! 3. **Hash-chained content addressing** — [`chain_hash`]: an append-only, tamper-evident DAG link
15//!    (BLAKE3 over `parent ‖ payload`); rewriting or dropping a record breaks every link after it.
16//!
17//! Symmetric AEAD is XChaCha20-Poly1305 (24-byte nonce). Sealed-box key/nonce are derived from the
18//! ECDH shared secret via BLAKE3 `derive_key` (domain-separated); each seal uses a fresh ephemeral
19//! key, so sealing is non-deterministic (no plaintext-equality leak) and nonce reuse is impossible.
20
21use chacha20poly1305::aead::{AeadInOut, KeyInit};
22use chacha20poly1305::XChaCha20Poly1305;
23use x25519_dalek::{PublicKey, StaticSecret};
24use zeroize::{Zeroize, ZeroizeOnDrop};
25
26const TAG_BYTES: usize = 16;
27const EPK_BYTES: usize = 32;
28const XNONCE_BYTES: usize = 24;
29
30const SEAL_KEY_CTX: &str = "q42:sanctuary:audit:seal:key:v1";
31const SEAL_NONCE_CTX: &str = "q42:sanctuary:audit:seal:nonce:v1";
32const CHAIN_HASH_LEN: usize = 32;
33
34/// Genesis parent for a fresh hash chain / DAG branch.
35pub const GENESIS_PARENT: [u8; CHAIN_HASH_LEN] = [0u8; CHAIN_HASH_LEN];
36
37#[derive(Debug, Clone, Copy, PartialEq, Eq)]
38pub enum SanctuaryAuditError {
39    Rng,
40    Encrypt,
41    Decrypt,
42    Malformed,
43}
44
45fn rand_bytes<const N: usize>() -> Result<[u8; N], SanctuaryAuditError> {
46    let mut b = [0u8; N];
47    getrandom::fill(&mut b).map_err(|_| SanctuaryAuditError::Rng)?;
48    Ok(b)
49}
50
51/// An audit keypair. The **public** key is exposed to any session (including the decoy) so it can
52/// append sealed records; the **secret** lives only in the real lane (wrapped under the real key)
53/// and is the sole means of reading them.
54#[derive(Zeroize, ZeroizeOnDrop)]
55pub struct AuditKeypair {
56    #[zeroize(skip)]
57    pub public: [u8; 32],
58    secret: [u8; 32],
59}
60
61impl AuditKeypair {
62    /// Generate a fresh keypair from the OS RNG. Fails with
63    /// `SanctuaryAuditError::Rng` when the system RNG is unavailable —
64    /// audit keys are never fabricated deterministically.
65    pub fn generate() -> Result<Self, SanctuaryAuditError> {
66        let secret = rand_bytes::<32>()?;
67        let public = PublicKey::from(&StaticSecret::from(secret)).to_bytes();
68        Ok(Self { public, secret })
69    }
70
71    /// Construct a keypair from a caller-supplied 32-byte secret (e.g. a KDF-derived key). Lets an envelope
72    /// keypair be **re-derived from a root secret** rather than stored at rest. `StaticSecret::from` clamps
73    /// the scalar deterministically, so any 32 bytes are a valid secret and `seal_to(public)` /
74    /// `open_sealed(secret)` stay consistent.
75    pub fn from_secret(secret: [u8; 32]) -> Self {
76        let public = PublicKey::from(&StaticSecret::from(secret)).to_bytes();
77        Self { public, secret }
78    }
79
80    /// The secret half — hold this only inside the real lane.
81    pub fn secret_bytes(&self) -> &[u8; 32] {
82        &self.secret
83    }
84}
85
86fn derive_seal_key_nonce(
87    shared: &[u8],
88    ephemeral_public: &[u8; 32],
89    recipient_public: &[u8; 32],
90) -> ([u8; 32], [u8; XNONCE_BYTES]) {
91    // Bind the derivation to both endpoints so a record can't be replayed under another recipient.
92    let mut km = Vec::with_capacity(shared.len() + 64);
93    km.extend_from_slice(shared);
94    km.extend_from_slice(ephemeral_public);
95    km.extend_from_slice(recipient_public);
96    let key = blake3::derive_key(SEAL_KEY_CTX, &km);
97    let nonce_full = blake3::derive_key(SEAL_NONCE_CTX, &km);
98    let mut nonce = [0u8; XNONCE_BYTES];
99    nonce.copy_from_slice(&nonce_full[..XNONCE_BYTES]);
100    (key, nonce)
101}
102
103fn cipher_for(key: &[u8; 32]) -> Result<XChaCha20Poly1305, SanctuaryAuditError> {
104    let key =
105        <&chacha20poly1305::Key>::try_from(&key[..]).map_err(|_| SanctuaryAuditError::Encrypt)?;
106    Ok(XChaCha20Poly1305::new(key))
107}
108
109fn aead_seal(
110    key: &[u8; 32],
111    nonce: &[u8; XNONCE_BYTES],
112    plaintext: &[u8],
113    aad: &[u8],
114) -> Result<Vec<u8>, SanctuaryAuditError> {
115    let cipher = cipher_for(key)?;
116    let nonce = <&chacha20poly1305::XNonce>::try_from(&nonce[..])
117        .map_err(|_| SanctuaryAuditError::Encrypt)?;
118    let mut buffer = plaintext.to_vec();
119    let tag = cipher
120        .encrypt_inout_detached(nonce, aad, buffer.as_mut_slice().into())
121        .map_err(|_| SanctuaryAuditError::Encrypt)?;
122    buffer.extend_from_slice(tag.as_slice());
123    Ok(buffer)
124}
125
126fn aead_open(
127    key: &[u8; 32],
128    nonce: &[u8; XNONCE_BYTES],
129    ct_and_tag: &[u8],
130    aad: &[u8],
131) -> Result<Vec<u8>, SanctuaryAuditError> {
132    if ct_and_tag.len() < TAG_BYTES {
133        return Err(SanctuaryAuditError::Malformed);
134    }
135    let split = ct_and_tag.len() - TAG_BYTES;
136    let (ct, tag_bytes) = ct_and_tag.split_at(split);
137    let cipher = cipher_for(key)?;
138    let nonce = <&chacha20poly1305::XNonce>::try_from(&nonce[..])
139        .map_err(|_| SanctuaryAuditError::Decrypt)?;
140    let tag = <&chacha20poly1305::Tag>::try_from(tag_bytes)
141        .map_err(|_| SanctuaryAuditError::Malformed)?;
142    let mut buffer = ct.to_vec();
143    cipher
144        .decrypt_inout_detached(nonce, aad, buffer.as_mut_slice().into(), tag)
145        .map_err(|_| SanctuaryAuditError::Decrypt)?;
146    Ok(buffer)
147}
148
149/// Seal `plaintext` so that only the holder of the secret matching `recipient_public` can open it.
150/// Anonymous: the sealer needs no identity, only the recipient's public key. Output layout:
151/// `ephemeral_public(32) ‖ ciphertext ‖ tag(16)`. Non-deterministic (fresh ephemeral key per call).
152pub fn seal_to(
153    recipient_public: &[u8; 32],
154    plaintext: &[u8],
155    aad: &[u8],
156) -> Result<Vec<u8>, SanctuaryAuditError> {
157    let ephemeral_secret = StaticSecret::from(rand_bytes::<32>()?);
158    let ephemeral_public = PublicKey::from(&ephemeral_secret).to_bytes();
159    let shared = ephemeral_secret.diffie_hellman(&PublicKey::from(*recipient_public));
160    let (key, nonce) =
161        derive_seal_key_nonce(shared.as_bytes(), &ephemeral_public, recipient_public);
162    let body = aead_seal(&key, &nonce, plaintext, aad)?;
163    let mut out = Vec::with_capacity(EPK_BYTES + body.len());
164    out.extend_from_slice(&ephemeral_public);
165    out.extend_from_slice(&body);
166    Ok(out)
167}
168
169/// Open a sealed box produced by [`seal_to`]. Requires the recipient secret; the public key alone
170/// cannot open it (that is the whole point — the decoy session writes but cannot read).
171pub fn open_sealed(
172    recipient_secret: &[u8; 32],
173    sealed: &[u8],
174    aad: &[u8],
175) -> Result<Vec<u8>, SanctuaryAuditError> {
176    if sealed.len() < EPK_BYTES + TAG_BYTES {
177        return Err(SanctuaryAuditError::Malformed);
178    }
179    let mut ephemeral_public = [0u8; 32];
180    ephemeral_public.copy_from_slice(&sealed[..EPK_BYTES]);
181    let body = &sealed[EPK_BYTES..];
182
183    let secret = StaticSecret::from(*recipient_secret);
184    let recipient_public = PublicKey::from(&secret).to_bytes();
185    let shared = secret.diffie_hellman(&PublicKey::from(ephemeral_public));
186    let (key, nonce) =
187        derive_seal_key_nonce(shared.as_bytes(), &ephemeral_public, &recipient_public);
188    aead_open(&key, &nonce, body, aad)
189}
190
191/// Wrap `key_material` under `wrapping_key` (AEAD). Output: `nonce(24) ‖ ciphertext ‖ tag(16)`.
192/// Used for the one-way hierarchy: the real lane key wraps the decoy key + the audit secret.
193pub fn wrap_key(
194    wrapping_key: &[u8; 32],
195    key_material: &[u8],
196    aad: &[u8],
197) -> Result<Vec<u8>, SanctuaryAuditError> {
198    let nonce = rand_bytes::<XNONCE_BYTES>()?;
199    let body = aead_seal(wrapping_key, &nonce, key_material, aad)?;
200    let mut out = Vec::with_capacity(XNONCE_BYTES + body.len());
201    out.extend_from_slice(&nonce);
202    out.extend_from_slice(&body);
203    Ok(out)
204}
205
206/// Unwrap a blob produced by [`wrap_key`]. Fails on the wrong key, wrong AAD, or tampering.
207pub fn unwrap_key(
208    wrapping_key: &[u8; 32],
209    wrapped: &[u8],
210    aad: &[u8],
211) -> Result<Vec<u8>, SanctuaryAuditError> {
212    if wrapped.len() < XNONCE_BYTES + TAG_BYTES {
213        return Err(SanctuaryAuditError::Malformed);
214    }
215    let mut nonce = [0u8; XNONCE_BYTES];
216    nonce.copy_from_slice(&wrapped[..XNONCE_BYTES]);
217    aead_open(wrapping_key, &nonce, &wrapped[XNONCE_BYTES..], aad)
218}
219
220/// One append-only DAG link: `BLAKE3(parent ‖ payload)`. Rewriting or reordering any record changes
221/// its hash and breaks the parent link of everything after it (tamper-evidence). Start a branch from
222/// [`GENESIS_PARENT`].
223pub fn chain_hash(parent: &[u8; CHAIN_HASH_LEN], payload: &[u8]) -> [u8; CHAIN_HASH_LEN] {
224    let mut hasher = blake3::Hasher::new();
225    hasher.update(parent);
226    hasher.update(payload);
227    *hasher.finalize().as_bytes()
228}
229
230#[cfg(test)]
231mod tests {
232    use super::*;
233
234    #[test]
235    fn sealed_box_round_trips() {
236        let kp = AuditKeypair::generate().unwrap();
237        let msg = b"decoy session 1: coercer added note at 12:04";
238        let sealed = seal_to(&kp.public, msg, b"branch:session-1").unwrap();
239        let opened = open_sealed(kp.secret_bytes(), &sealed, b"branch:session-1").unwrap();
240        assert_eq!(opened, msg);
241    }
242
243    #[test]
244    fn only_the_secret_holder_can_open() {
245        let kp = AuditKeypair::generate().unwrap();
246        let other = AuditKeypair::generate().unwrap();
247        let sealed = seal_to(&kp.public, b"evidence", b"").unwrap();
248        assert!(open_sealed(other.secret_bytes(), &sealed, b"").is_err());
249    }
250
251    #[test]
252    fn public_key_alone_cannot_read() {
253        // The whole point: the decoy session holds only the public key and must not be able to read
254        // what it sealed. Using the public bytes as if they were the secret does not recover it.
255        let kp = AuditKeypair::generate().unwrap();
256        let sealed = seal_to(&kp.public, b"only-the-real-lane-reads-this", b"").unwrap();
257        match open_sealed(&kp.public, &sealed, b"") {
258            Err(_) => {}
259            Ok(pt) => assert_ne!(pt.as_slice(), b"only-the-real-lane-reads-this"),
260        }
261    }
262
263    #[test]
264    fn tampered_sealed_box_is_rejected() {
265        let kp = AuditKeypair::generate().unwrap();
266        let mut sealed = seal_to(&kp.public, b"unaltered", b"").unwrap();
267        let mid = sealed.len() / 2;
268        sealed[mid] ^= 0xFF;
269        assert!(open_sealed(kp.secret_bytes(), &sealed, b"").is_err());
270    }
271
272    #[test]
273    fn aad_is_bound() {
274        let kp = AuditKeypair::generate().unwrap();
275        let sealed = seal_to(&kp.public, b"m", b"branch:session-1").unwrap();
276        assert!(open_sealed(kp.secret_bytes(), &sealed, b"branch:session-2").is_err());
277    }
278
279    #[test]
280    fn sealing_is_non_deterministic() {
281        // Fresh ephemeral key per seal => identical plaintext yields distinct ciphertext (no
282        // equality leak to whoever can see the audit region).
283        let kp = AuditKeypair::generate().unwrap();
284        let a = seal_to(&kp.public, b"same-note", b"").unwrap();
285        let b = seal_to(&kp.public, b"same-note", b"").unwrap();
286        assert_ne!(a, b);
287    }
288
289    #[test]
290    fn key_wrap_round_trips_and_binds_key_and_aad() {
291        let real_key = rand_bytes::<32>().unwrap();
292        let decoy_key = [7u8; 32];
293        let wrapped = wrap_key(&real_key, &decoy_key, b"role:decoy-lane-key").unwrap();
294        assert_eq!(
295            unwrap_key(&real_key, &wrapped, b"role:decoy-lane-key").unwrap(),
296            decoy_key
297        );
298        // Wrong wrapping key (the decoy cannot reach up).
299        assert!(unwrap_key(&[9u8; 32], &wrapped, b"role:decoy-lane-key").is_err());
300        // Wrong AAD.
301        assert!(unwrap_key(&real_key, &wrapped, b"role:something-else").is_err());
302    }
303
304    #[test]
305    fn hash_chain_is_deterministic_and_tamper_evident() {
306        let r1 = chain_hash(&GENESIS_PARENT, b"session-1 opened");
307        let r2 = chain_hash(&r1, b"note added: 'call me'");
308        let r3 = chain_hash(&r2, b"note edited");
309
310        // Deterministic.
311        assert_eq!(r1, chain_hash(&GENESIS_PARENT, b"session-1 opened"));
312        assert_ne!(r1, r2);
313        assert_ne!(r2, r3);
314
315        // Rewrite record 2's payload => r2 changes => r3's parent link no longer matches.
316        let r2_tampered = chain_hash(&r1, b"note added: 'do NOT call'");
317        assert_ne!(r2, r2_tampered);
318        assert_ne!(r3, chain_hash(&r2_tampered, b"note edited"));
319    }
320}