Skip to main content

qualia_client_core/
envelope_encryption.rs

1//! **Real envelope encryption for the accountability commons payload** — the crypto that makes
2//! [`ConsentCredential`](crate::consent_credential::ConsentCredential)'s "revoke destroys the wrapped key ⇒
3//! no key, no payload" a *fact*, not a model with opaque placeholder bytes.
4//!
5//! Two layers, both real (built on the already-tested `qualia_core_db::crypto::sanctuary_audit` primitives —
6//! X25519 sealed boxes + XChaCha20-Poly1305 AEAD; no new crate, no simulation):
7//!
8//! 1. **Payload layer (symmetric).** A random **data-encryption key (DEK)** encrypts the plaintext with an
9//!    AEAD ([`wrap_key`]); the ciphertext is content-addressed (`commitment = SHA-256(ciphertext)`), giving
10//!    the [`EncryptedCommonsPayload`] that many parties may replicate. Opening verifies the commitment (the
11//!    bytes are the committed bytes) *then* AEAD-decrypts (tamper ⇒ failure).
12//! 2. **Key layer (asymmetric, per recipient).** The DEK is **sealed to a recipient's public key**
13//!    ([`seal_to`]) — an anonymous ephemeral-DH box only that recipient's secret can open. This sealed DEK
14//!    **is** the credential's `wrapped_key`. So access is genuinely per-holder, and **revocation = destroying
15//!    that sealed DEK** ([`ConsentCredential::revoke`](crate::consent_credential::ConsentCredential::revoke)):
16//!    the recipient can no longer recover the DEK, and the ciphertext — wherever replicated — is opaque to
17//!    them. When **no** live credential holds a sealed DEK for a payload, the DEK is unrecoverable and the
18//!    payload is **crypto-shredded** (permanently unreadable though the bytes survive), exactly as the model
19//!    promised.
20//!
21//! Native-only (the sealed-box primitives are `not(wasm32)`; the desktop owns keys), matching
22//! `wellfair::sanctuary_vault`.
23//!
24//! What this does **not** yet do (named honestly, not deferred behind a lane): distribute a *remote* agent's
25//! X25519 public key — that comes from the peer's published key material in the connection/identity layer
26//! (`social_peers` / DID document), so a worker on their own device can be sealed to and decrypt
27//! independently. Until that is wired, the host seals to the **owner's** envelope keypair by default (the
28//! owner can always open their own data), and can seal to any supplied recipient public key.
29//!
30//! [`wrap_key`]: qualia_core_db::crypto::sanctuary_audit::wrap_key
31//! [`seal_to`]: qualia_core_db::crypto::sanctuary_audit::seal_to
32//! [`EncryptedCommonsPayload`]: crate::consent_credential::EncryptedCommonsPayload
33
34use qualia_core_db::crypto::sanctuary_audit::{
35    open_sealed, seal_to, unwrap_key, wrap_key, AuditKeypair,
36};
37use sha2::{Digest, Sha256};
38
39use crate::consent_credential::{EncryptedCommonsPayload, PayloadCommitment};
40
41/// AEAD associated-data domain separator for the payload layer (binds ciphertext to this use).
42const PAYLOAD_AAD: &[u8] = b"qualia:accountability:payload:v1";
43/// AEAD associated-data domain separator for the sealed DEK (the wrapped key).
44const DEK_AAD: &[u8] = b"qualia:accountability:dek:v1";
45
46/// A 32-byte data-encryption key. Secret: seal it to a recipient, never store it in the clear.
47pub type DataKey = [u8; 32];
48
49/// An X25519 envelope keypair for a party (the owner, or an agent). The **secret** opens sealed DEKs; the
50/// **public** is what a DEK is sealed *to*.
51#[derive(Debug, Clone, PartialEq, Eq)]
52pub struct EnvelopeKeypair {
53    pub public: [u8; 32],
54    pub secret: [u8; 32],
55}
56
57impl EnvelopeKeypair {
58    /// Generate a fresh keypair (real X25519, OS randomness).
59    pub fn generate() -> Result<Self, String> {
60        let kp = AuditKeypair::generate().map_err(|e| format!("keypair generate: {e:?}"))?;
61        Ok(Self {
62            public: kp.public,
63            secret: *kp.secret_bytes(),
64        })
65    }
66
67    /// Public key as hex.
68    pub fn public_hex(&self) -> String {
69        hex::encode(self.public)
70    }
71    /// Secret key as hex.
72    pub fn secret_hex(&self) -> String {
73        hex::encode(self.secret)
74    }
75
76    /// Reconstruct from stored hex (e.g. an agent keypair supplied for opening).
77    pub fn from_hex(public_hex: &str, secret_hex: &str) -> Result<Self, String> {
78        Ok(Self {
79            public: parse_key_hex(public_hex, "public")?,
80            secret: parse_key_hex(secret_hex, "secret")?,
81        })
82    }
83
84    /// **Derive** a keypair deterministically from a root secret (the owner's ed25519 signing-key seed) and a
85    /// domain tag, so the **owner envelope keypair is re-derivable and NEVER stored at rest** — no plaintext
86    /// X25519 secret on disk. The derivation is `SHA-256(domain ‖ 0x1f ‖ root_secret)` → X25519 secret; it is
87    /// stable, so seals to this public key open with the re-derived secret across sessions.
88    pub fn derive(root_secret: &[u8; 32], domain: &[u8]) -> Self {
89        let mut h = Sha256::new();
90        h.update(domain);
91        h.update(b"\x1f");
92        h.update(root_secret);
93        let derived: [u8; 32] = h.finalize().into();
94        let kp = AuditKeypair::from_secret(derived);
95        Self {
96            public: kp.public,
97            secret: *kp.secret_bytes(),
98        }
99    }
100}
101
102/// Domain tag for deriving the owner's envelope keypair from their ed25519 signing-key seed.
103pub const OWNER_ENVELOPE_DOMAIN: &[u8] = b"qualia:accountability:envelope:owner:v1";
104
105/// Domain tag for deriving the owner's post-quantum hybrid KEM key seed (X-Wing: ML-KEM-768 + X25519).
106pub const OWNER_PQ_KEM_DOMAIN: &[u8] = b"qualia:accountability:pq-kem:xwing-mlkem768:v1";
107/// Domain tag for deriving the owner's post-quantum digital signature key seed (ML-DSA-65).
108pub const OWNER_PQ_DSA_DOMAIN: &[u8] = b"qualia:accountability:pq-dsa:mldsa65:v1";
109
110/// Post-quantum key material deterministically derived from a root secret.
111/// Provides domain-separated seeds for X-Wing (ML-KEM-768 + X25519) and ML-DSA-65,
112/// enabling the host keystore to derive keys at runtime without storing plaintext secret keys on disk.
113#[derive(Debug, Clone, PartialEq, Eq)]
114pub struct PostQuantumKeyMaterial {
115    /// 64-byte seed for X-Wing: 32 bytes for ML-KEM-768 (d || z) and 32 bytes for X25519 per X-Wing spec.
116    pub xwing_seed: [u8; 64],
117    /// 32-byte seed for ML-DSA-65.
118    pub mldsa65_seed: [u8; 32],
119}
120
121impl PostQuantumKeyMaterial {
122    /// Deterministically derive post-quantum key seeds from a root secret (e.g. ed25519 signing seed).
123    /// Uses domain separation to generate distinct seeds for X-Wing (ML-KEM-768 + X25519) and ML-DSA-65.
124    pub fn derive_from_root(root_secret: &[u8; 32]) -> Self {
125        // ML-KEM-768 seed component of X-Wing (32 bytes)
126        let mut h_kem = Sha256::new();
127        h_kem.update(OWNER_PQ_KEM_DOMAIN);
128        h_kem.update(b"\x00");
129        h_kem.update(root_secret);
130        let kem_seed: [u8; 32] = h_kem.finalize().into();
131
132        // X25519 seed component of X-Wing (32 bytes)
133        let mut h_x25519 = Sha256::new();
134        h_x25519.update(OWNER_PQ_KEM_DOMAIN);
135        h_x25519.update(b"\x01");
136        h_x25519.update(root_secret);
137        let x25519_seed: [u8; 32] = h_x25519.finalize().into();
138
139        let mut xwing_seed = [0u8; 64];
140        xwing_seed[..32].copy_from_slice(&kem_seed);
141        xwing_seed[32..].copy_from_slice(&x25519_seed);
142
143        // ML-DSA-65 seed (32 bytes)
144        let mut h_dsa = Sha256::new();
145        h_dsa.update(OWNER_PQ_DSA_DOMAIN);
146        h_dsa.update(b"\x1f");
147        h_dsa.update(root_secret);
148        let mldsa65_seed: [u8; 32] = h_dsa.finalize().into();
149
150        Self {
151            xwing_seed,
152            mldsa65_seed,
153        }
154    }
155
156    /// Key ID for the post-quantum key material, deterministically computed from the seeds.
157    pub fn key_id(&self) -> String {
158        let mut h = Sha256::new();
159        h.update(b"qualia:accountability:pq-key-id:v1\x1f");
160        h.update(&self.xwing_seed);
161        h.update(&self.mldsa65_seed);
162        let d = h.finalize();
163        format!("pq:{}", hex::encode(&d[..16]))
164    }
165}
166
167fn parse_key_hex(s: &str, which: &str) -> Result<[u8; 32], String> {
168    let bytes = hex::decode(s.trim()).map_err(|e| format!("{which} key not hex: {e}"))?;
169    bytes
170        .as_slice()
171        .try_into()
172        .map_err(|_| format!("{which} key must be 32 bytes, got {}", bytes.len()))
173}
174
175/// A fresh random DEK (four 64-bit draws from the OS RNG — the API `rand::random::<u64>()` in use elsewhere).
176fn random_dek() -> DataKey {
177    let mut k = [0u8; 32];
178    for chunk in k.chunks_mut(8) {
179        let r = rand::random::<u64>().to_le_bytes();
180        chunk.copy_from_slice(&r[..chunk.len()]);
181    }
182    k
183}
184
185/// **Seal a plaintext payload.** Generates a random DEK, AEAD-encrypts under it, and content-addresses the
186/// ciphertext. Returns the replicable [`EncryptedCommonsPayload`] and the DEK (to be sealed per recipient by
187/// [`wrap_dek_to`], then dropped — do not persist it in the clear).
188pub fn seal_payload(
189    plaintext: &[u8],
190    storers: Vec<String>,
191) -> Result<(EncryptedCommonsPayload, DataKey), String> {
192    let dek = random_dek();
193    let ciphertext =
194        wrap_key(&dek, plaintext, PAYLOAD_AAD).map_err(|e| format!("seal payload: {e:?}"))?;
195    let commitment: PayloadCommitment = Sha256::digest(&ciphertext).into();
196    Ok((
197        EncryptedCommonsPayload::new(commitment, ciphertext, storers),
198        dek,
199    ))
200}
201
202/// **Seal (wrap) a DEK to a recipient's public key** — the credential's `wrapped_key`. Only the holder of
203/// the matching secret can [`unwrap_dek`] it; destroying this blob (revocation) removes that access.
204pub fn wrap_dek_to(recipient_public: &[u8; 32], dek: &DataKey) -> Result<Vec<u8>, String> {
205    seal_to(recipient_public, dek, DEK_AAD).map_err(|e| format!("wrap DEK: {e:?}"))
206}
207
208/// **Unwrap a DEK** with the recipient's secret key. Fails for the wrong recipient or a tampered blob.
209pub fn unwrap_dek(recipient_secret: &[u8; 32], wrapped: &[u8]) -> Result<DataKey, String> {
210    let opened = open_sealed(recipient_secret, wrapped, DEK_AAD)
211        .map_err(|e| format!("unwrap DEK: {e:?}"))?;
212    opened
213        .as_slice()
214        .try_into()
215        .map_err(|_| "unwrapped DEK was not 32 bytes".to_string())
216}
217
218/// **Open a payload** with the DEK — verifies the content-address commitment (the bytes are the committed
219/// bytes) *then* AEAD-decrypts. Any tamper (to ciphertext or a swapped payload) fails.
220pub fn open_payload(payload: &EncryptedCommonsPayload, dek: &DataKey) -> Result<Vec<u8>, String> {
221    let recomputed: PayloadCommitment = Sha256::digest(&payload.ciphertext).into();
222    if recomputed != payload.commitment {
223        return Err("commitment mismatch — ciphertext is not the committed bytes".into());
224    }
225    unwrap_key(dek, &payload.ciphertext, PAYLOAD_AAD).map_err(|e| format!("open payload: {e:?}"))
226}
227
228/// **Open a payload directly from a recipient's secret + the credential's wrapped DEK.** The end-to-end
229/// decrypt path: unwrap the sealed DEK, then open the payload. If the wrapped DEK is absent (revoked), the
230/// caller has nothing to pass here — that is the crypto-enforced revocation.
231pub fn open_payload_with_wrapped(
232    payload: &EncryptedCommonsPayload,
233    recipient_secret: &[u8; 32],
234    wrapped_dek: &[u8],
235) -> Result<Vec<u8>, String> {
236    let dek = unwrap_dek(recipient_secret, wrapped_dek)?;
237    open_payload(payload, &dek)
238}
239
240#[cfg(test)]
241mod tests {
242    use super::*;
243
244    #[test]
245    fn seal_wrap_unwrap_open_round_trips() {
246        let owner = EnvelopeKeypair::generate().unwrap();
247        let agent = EnvelopeKeypair::generate().unwrap();
248        let plaintext = b"housing record: emergency placement requested 2026-07-06";
249
250        // Owner seals the payload and seals the DEK to the agent.
251        let (payload, dek) = seal_payload(plaintext, vec!["did:wf:person".into()]).unwrap();
252        assert_ne!(
253            payload.ciphertext.as_slice(),
254            plaintext,
255            "payload is really encrypted"
256        );
257        let wrapped = wrap_dek_to(&agent.public, &dek).unwrap();
258
259        // The agent (their secret) recovers the DEK and opens the payload.
260        let opened = open_payload_with_wrapped(&payload, &agent.secret, &wrapped).unwrap();
261        assert_eq!(
262            opened.as_slice(),
263            plaintext,
264            "agent decrypts the exact plaintext"
265        );
266
267        // The owner can also seal-to-self and open (data returns to the person).
268        let wrapped_self = wrap_dek_to(&owner.public, &dek).unwrap();
269        assert_eq!(
270            open_payload_with_wrapped(&payload, &owner.secret, &wrapped_self)
271                .unwrap()
272                .as_slice(),
273            plaintext
274        );
275    }
276
277    #[test]
278    fn wrong_recipient_cannot_unwrap_the_dek() {
279        let agent = EnvelopeKeypair::generate().unwrap();
280        let attacker = EnvelopeKeypair::generate().unwrap();
281        let (_payload, dek) = seal_payload(b"secret", vec![]).unwrap();
282        let wrapped = wrap_dek_to(&agent.public, &dek).unwrap();
283        // A different secret cannot open the sealed DEK.
284        assert!(
285            unwrap_dek(&attacker.secret, &wrapped).is_err(),
286            "only the intended recipient unwraps"
287        );
288    }
289
290    #[test]
291    fn revocation_destroying_the_wrapped_dek_makes_the_payload_unrecoverable() {
292        // Model the credential holding the wrapped DEK; revocation drops it. Without it there is no path to
293        // the DEK, so the ciphertext (however replicated) cannot be opened.
294        let agent = EnvelopeKeypair::generate().unwrap();
295        let (payload, dek) = seal_payload(
296            b"the record",
297            vec!["did:wf:person".into(), "did:wf:archive".into()],
298        )
299        .unwrap();
300        let wrapped = Some(wrap_dek_to(&agent.public, &dek).unwrap());
301
302        // Live: the agent opens it.
303        assert!(
304            open_payload_with_wrapped(&payload, &agent.secret, wrapped.as_ref().unwrap()).is_ok()
305        );
306
307        // Revoke: the wrapped DEK is destroyed. The payload bytes survive (still replicated) but there is
308        // nothing to unwrap — the DEK cannot be recovered, so the payload is crypto-shredded for this holder.
309        let wrapped: Option<Vec<u8>> = None;
310        assert!(wrapped.is_none());
311        assert!(
312            payload.is_durable(),
313            "the commons bytes are NOT chased down — they survive"
314        );
315        // With no wrapped DEK and no other key, an attempt with a guessed/zero DEK fails (AEAD).
316        assert!(
317            open_payload(&payload, &[0u8; 32]).is_err(),
318            "no key, no payload"
319        );
320    }
321
322    #[test]
323    fn a_tampered_ciphertext_is_rejected() {
324        let agent = EnvelopeKeypair::generate().unwrap();
325        let (mut payload, dek) = seal_payload(b"unaltered record", vec![]).unwrap();
326        let wrapped = wrap_dek_to(&agent.public, &dek).unwrap();
327        // Flip a byte in the ciphertext. The commitment now mismatches (content-address), and even past that
328        // the AEAD tag would fail.
329        let mid = payload.ciphertext.len() / 2;
330        payload.ciphertext[mid] ^= 0xFF;
331        assert!(
332            open_payload_with_wrapped(&payload, &agent.secret, &wrapped).is_err(),
333            "tamper is detected"
334        );
335    }
336
337    #[test]
338    fn a_swapped_ciphertext_breaks_the_commitment() {
339        let (mut a, _dek_a) = seal_payload(b"record A", vec![]).unwrap();
340        let (b, _dek_b) = seal_payload(b"record B", vec![]).unwrap();
341        // Substitute B's ciphertext under A's commitment — the content-address check catches it.
342        a.ciphertext = b.ciphertext;
343        assert!(
344            open_payload(&a, &[0u8; 32]).is_err(),
345            "commitment binds the ciphertext"
346        );
347    }
348
349    #[test]
350    fn derived_owner_keypair_is_deterministic_and_usable() {
351        let seed = [42u8; 32]; // stands in for the owner's ed25519 signing-key seed
352        let a = EnvelopeKeypair::derive(&seed, OWNER_ENVELOPE_DOMAIN);
353        let b = EnvelopeKeypair::derive(&seed, OWNER_ENVELOPE_DOMAIN);
354        assert_eq!(
355            a, b,
356            "same seed + domain ⇒ same keypair (re-derivable, nothing stored)"
357        );
358        // A different domain (or seed) gives an independent keypair.
359        assert_ne!(a, EnvelopeKeypair::derive(&seed, b"other:domain"));
360        assert_ne!(
361            a,
362            EnvelopeKeypair::derive(&[7u8; 32], OWNER_ENVELOPE_DOMAIN)
363        );
364        // And it actually works as an envelope key: seal to it, re-derive, open.
365        let (payload, dek) = seal_payload(b"owner-held record", vec![]).unwrap();
366        let wrapped = wrap_dek_to(&a.public, &dek).unwrap();
367        let rederived = EnvelopeKeypair::derive(&seed, OWNER_ENVELOPE_DOMAIN);
368        assert_eq!(
369            open_payload_with_wrapped(&payload, &rederived.secret, &wrapped)
370                .unwrap()
371                .as_slice(),
372            b"owner-held record"
373        );
374    }
375
376    #[test]
377    fn keypair_hex_round_trips() {
378        let kp = EnvelopeKeypair::generate().unwrap();
379        let back = EnvelopeKeypair::from_hex(&kp.public_hex(), &kp.secret_hex()).unwrap();
380        assert_eq!(kp, back);
381        assert!(EnvelopeKeypair::from_hex("zz", &kp.secret_hex()).is_err());
382    }
383
384    #[test]
385    fn pq_key_material_deterministic_derivation() {
386        let root = [99u8; 32];
387        let pq1 = PostQuantumKeyMaterial::derive_from_root(&root);
388        let pq2 = PostQuantumKeyMaterial::derive_from_root(&root);
389        assert_eq!(pq1, pq2, "derivation must be deterministic");
390        assert_eq!(pq1.key_id(), pq2.key_id(), "key_id must be deterministic");
391
392        let root_other = [100u8; 32];
393        let pq_other = PostQuantumKeyMaterial::derive_from_root(&root_other);
394        assert_ne!(pq1, pq_other);
395        assert_ne!(pq1.key_id(), pq_other.key_id());
396    }
397
398    #[test]
399    fn pq_key_material_domain_separation() {
400        let root = [42u8; 32];
401        let pq = PostQuantumKeyMaterial::derive_from_root(&root);
402        let classical = EnvelopeKeypair::derive(&root, OWNER_ENVELOPE_DOMAIN);
403
404        // ML-KEM vs X25519 within X-Wing
405        assert_ne!(&pq.xwing_seed[..32], &pq.xwing_seed[32..]);
406        // X-Wing parts vs ML-DSA
407        assert_ne!(&pq.xwing_seed[..32], &pq.mldsa65_seed[..]);
408        assert_ne!(&pq.xwing_seed[32..], &pq.mldsa65_seed[..]);
409        // PQ seeds vs classical secret
410        assert_ne!(&pq.xwing_seed[..32], &classical.secret[..]);
411        assert_ne!(&pq.xwing_seed[32..], &classical.secret[..]);
412        assert_ne!(&pq.mldsa65_seed[..], &classical.secret[..]);
413    }
414
415    #[test]
416    fn pq_key_material_key_id_stability() {
417        let root = [1u8; 32];
418        let pq = PostQuantumKeyMaterial::derive_from_root(&root);
419        let id = pq.key_id();
420        assert!(id.starts_with("pq:"));
421        assert_eq!(id.len(), 3 + 32); // "pq:" + 16 bytes hex (32 chars)
422        // Repeat to ensure stability
423        assert_eq!(id, pq.key_id());
424    }
425}