Skip to main content

qualia_core_db/identity/
agency.rs

1use crate::NQuin;
2use ed25519_dalek::{Signature, Signer, SigningKey, Verifier, VerifyingKey};
3use sha2::{Digest, Sha256};
4
5#[derive(Debug, PartialEq, Eq)]
6pub enum AgencyError {
7    InvalidSignature,
8    TamperedData,
9}
10
11/// Computes the Author-Scoped Merkle Sub-Root Hash for a specific user's claims.
12/// It partitions the 128KB frame by the Author's DID, strictly ignoring claims
13/// authored by other actors in the Bilateral frame.
14/// Uses zero-allocation iteration over the existing memory slice.
15pub fn compute_scoped_merkle_root(frame: &[NQuin], author_did: u64) -> [u8; 32] {
16    let mut hasher = Sha256::new();
17
18    // Iterate through the frame without allocating Vectors or Strings
19    for quin in frame.iter() {
20        // In Qualia-DB, the Author's DID is embedded in the Context vector
21        if quin.context == author_did {
22            // Hash the 48-byte Quin structure natively
23            // `bytemuck::bytes_of` safely casts the struct to a byte slice since it implements Pod.
24            let bytes: &[u8; 48] = bytemuck::cast_ref(quin);
25            hasher.update(bytes);
26        }
27    }
28
29    // Finalize the Merkle Sub-Root hash (32 bytes)
30    let result = hasher.finalize();
31    let mut root_hash = [0u8; 32];
32    root_hash.copy_from_slice(&result);
33    root_hash
34}
35
36/// The Human Agency Hook
37/// Generates a 64-byte Ed25519 signature exclusively over the Author-Scoped Merkle Sub-Root.
38pub fn sign_agency_root(signing_key: &SigningKey, sub_root_hash: &[u8; 32]) -> Signature {
39    // The Ed25519-dalek library natively signs raw byte arrays.
40    signing_key.sign(sub_root_hash)
41}
42
43/// The Verification Gate
44/// Validates an incoming 64-byte signature against the author's Public Key (`VerifyingKey`).
45/// Only validates the specific claims matching the author's DID, ensuring Bilateral Integrity.
46pub fn verify_human_agency(
47    frame: &[NQuin],
48    author_did: u64,
49    verifying_key: &VerifyingKey,
50    signature: &Signature,
51) -> Result<(), AgencyError> {
52    // 1. Recompute the Author-Scoped Merkle Sub-Root from the incoming frame
53    let expected_sub_root = compute_scoped_merkle_root(frame, author_did);
54
55    // 2. Validate the signature mathematically
56    if verifying_key.verify(&expected_sub_root, signature).is_ok() {
57        Ok(())
58    } else {
59        Err(AgencyError::InvalidSignature)
60    }
61}
62
63/// Sign an Author-Scoped Merkle Sub-Root with post-quantum ML-DSA-65 (FIPS-204).
64///
65/// Caller supplies the fixed-size 3309-byte output buffer for the signature.
66/// Zero heap allocations.
67pub fn sign_agency_root_pq(
68    signing_key: &[u8; crate::crypto::network::types::ML_DSA_65_SK_LEN],
69    sub_root_hash: &[u8; 32],
70    out_sig: &mut [u8; crate::crypto::network::types::ML_DSA_65_SIG_LEN],
71) -> Result<(), AgencyError> {
72    use fips204::ml_dsa_65::PrivateKey;
73    use fips204::traits::{SerDes, Signer};
74
75    let Ok(sk) = PrivateKey::try_from_bytes(*signing_key) else {
76        return Err(AgencyError::InvalidSignature);
77    };
78    let Ok(sig) = sk.try_sign(sub_root_hash, b"qualia:agency:pq:v1") else {
79        return Err(AgencyError::InvalidSignature);
80    };
81    out_sig.copy_from_slice(&sig);
82    Ok(())
83}
84
85/// Verify an Author-Scoped Merkle Sub-Root with post-quantum ML-DSA-65 (FIPS-204).
86///
87/// Validates an incoming 3309-byte FIPS-204 signature against the author's
88/// 1952-byte ML-DSA-65 public key over the author-scoped Merkle sub-root.
89/// Guaranteed zero heap allocations in hot path.
90pub fn verify_human_agency_pq(
91    frame: &[NQuin],
92    author_did: u64,
93    public_key: &[u8; crate::crypto::network::types::ML_DSA_65_PK_LEN],
94    signature: &[u8; crate::crypto::network::types::ML_DSA_65_SIG_LEN],
95) -> Result<(), AgencyError> {
96    use fips204::ml_dsa_65::PublicKey;
97    use fips204::traits::{SerDes, Verifier};
98
99    let expected_sub_root = compute_scoped_merkle_root(frame, author_did);
100
101    let Ok(pk) = PublicKey::try_from_bytes(*public_key) else {
102        return Err(AgencyError::InvalidSignature);
103    };
104
105    if pk.verify(&expected_sub_root, signature, b"qualia:agency:pq:v1") {
106        Ok(())
107    } else {
108        Err(AgencyError::InvalidSignature)
109    }
110}
111
112/// Sign an Author-Scoped Merkle Sub-Root with hybrid DualProof (ML-DSA-65 + Ed25519).
113///
114/// Produces both post-quantum and classical signatures over the identical Merkle sub-root.
115/// Zero heap allocations.
116pub fn sign_agency_root_dual(
117    mldsa_sk: &[u8; crate::crypto::network::types::ML_DSA_65_SK_LEN],
118    ed25519_seed: &[u8; 32],
119    sub_root_hash: &[u8; 32],
120    out: &mut crate::crypto::network::dual_sign::DualProof,
121) -> Result<(), AgencyError> {
122    crate::crypto::network::dual_sign::sign_dual(
123        mldsa_sk,
124        ed25519_seed,
125        sub_root_hash,
126        b"qualia:agency:dual:v1",
127        out,
128    )
129    .map_err(|_| AgencyError::InvalidSignature)
130}
131
132/// Verify an Author-Scoped Merkle Sub-Root with hybrid DualProof (ML-DSA-65 + Ed25519).
133///
134/// Both signatures must verify mathematically over the recomputed Merkle sub-root.
135/// If either fails, the transaction is rejected.
136/// Guaranteed zero heap allocations in hot path.
137pub fn verify_human_agency_dual(
138    frame: &[NQuin],
139    author_did: u64,
140    ed25519_pk: &[u8; crate::crypto::network::types::ED25519_PK_LEN],
141    mldsa_pk: &[u8; crate::crypto::network::types::ML_DSA_65_PK_LEN],
142    proof: &crate::crypto::network::dual_sign::DualProof,
143) -> Result<(), AgencyError> {
144    let expected_sub_root = compute_scoped_merkle_root(frame, author_did);
145
146    crate::crypto::network::dual_sign::verify_dual(
147        mldsa_pk,
148        ed25519_pk,
149        &expected_sub_root,
150        b"qualia:agency:dual:v1",
151        proof,
152    )
153    .map_err(|_| AgencyError::InvalidSignature)
154}
155
156/// Stamp fiduciary metadata and refresh the XOR parity block before WAL commit.
157/// `principal_did_hash` is embedded in `context`; agent identity in metadata low bits.
158pub fn stamp_fiduciary_metadata(quin: &mut NQuin, principal_did_hash: u64, agent_did_hash: u64) {
159    quin.context = principal_did_hash;
160    let agent_lane = agent_did_hash & 0xFFFF;
161    let principal_clock = (principal_did_hash >> 16) & 0x1FFF_FFFF;
162    quin.metadata = agent_lane | (principal_clock << 16);
163    quin.parity = quin.subject ^ quin.predicate ^ quin.object ^ quin.context ^ quin.metadata;
164}
165
166/// Volatile zero of all Quin fields after WAL commit (wipes transient LLM state).
167pub fn scrub_quin_volatile(quin: &mut NQuin) {
168    unsafe {
169        std::ptr::write_volatile(&mut quin.subject, 0);
170        std::ptr::write_volatile(&mut quin.predicate, 0);
171        std::ptr::write_volatile(&mut quin.object, 0);
172        std::ptr::write_volatile(&mut quin.context, 0);
173        std::ptr::write_volatile(&mut quin.metadata, 0);
174        std::ptr::write_volatile(&mut quin.parity, 0);
175    }
176}
177
178/// Sign a single graph-mutation Quin using the author-scoped Merkle sub-root.
179pub fn sign_graph_mutation(signing_key: &SigningKey, quin: &NQuin) -> Signature {
180    let frame = [*quin];
181    let root = compute_scoped_merkle_root(&frame, quin.context);
182    sign_agency_root(signing_key, &root)
183}
184
185/// Derives a 32-byte AES-256-GCM key from the user's PIN for Deniable Encryption (Sanctuary Mode).
186/// By passing different PINs, different keys are derived, which unlocks different DB Lanes.
187/// The decoy lane operates exactly identically to the sanctuary lane.
188#[cfg(all(feature = "sanctuary-crypto", not(target_arch = "wasm32")))]
189const LANE_KEY_LENGTH: usize = 32;
190
191#[cfg(all(feature = "sanctuary-crypto", not(target_arch = "wasm32")))]
192/// `?::derive_lane_key`.
193pub fn derive_lane_key(pin: &str, salt: &[u8]) -> [u8; LANE_KEY_LENGTH] {
194    crate::sanctuary_crypto::derive_lane_cipher_key(
195        pin.as_bytes(),
196        salt,
197        crate::sanctuary_crypto::DEFAULT_PBKDF2_ITERATIONS,
198    )
199}
200
201#[cfg(all(feature = "sanctuary-crypto", not(target_arch = "wasm32")))]
202/// Memory-hard Argon2id + HKDF-SHA256 domain-separated Sanctuary Keep lane key derivation (WP-05).
203///
204/// Combines Argon2id memory-hardness with HKDF-SHA256 sub-lane expansion so multi-member
205/// family/household and multi-tenant VPS vaults isolate each member's Sanctuary Keep lane.
206pub fn derive_lane_key_argon2_hkdf(
207    pin: &str,
208    salt: &[u8],
209    lane_domain: &[u8],
210    m_cost_kib: u32,
211    t_cost: u32,
212    p_cost: u32,
213) -> Result<[u8; LANE_KEY_LENGTH], String> {
214    use hmac::{Hmac, Mac};
215    type HmacSha256 = Hmac<Sha256>;
216
217    // Ensure salt is at least 8 bytes for Argon2id
218    let mut padded_salt = [0u8; 16];
219    let salt_slice = if salt.len() >= 8 {
220        salt
221    } else {
222        padded_salt[..salt.len()].copy_from_slice(salt);
223        &padded_salt[..]
224    };
225
226    let km = crate::sanctuary_crypto::derive_sanctuary_key_material_argon2(
227        pin.as_bytes(),
228        salt_slice,
229        m_cost_kib,
230        t_cost,
231        p_cost,
232    )?;
233
234    // HKDF-Extract(salt = volume_tweak, IKM = cipher_key)
235    let mut extract_mac = <HmacSha256 as hmac::digest::KeyInit>::new_from_slice(&km.volume_tweak)
236        .map_err(|e| format!("hkdf extract init: {e}"))?;
237    extract_mac.update(&km.cipher_key);
238    let prk = extract_mac.finalize().into_bytes();
239
240    // HKDF-Expand(PRK, info = "qualia.sanctuary.lane.v1|" || lane_domain || 0x01, L = 32)
241    let mut expand_mac = <HmacSha256 as hmac::digest::KeyInit>::new_from_slice(&prk)
242        .map_err(|e| format!("hkdf expand init: {e}"))?;
243    expand_mac.update(b"qualia.sanctuary.lane.v1|");
244    expand_mac.update(lane_domain);
245    expand_mac.update(&[0x01]);
246    let okm = expand_mac.finalize().into_bytes();
247
248    let mut out = [0u8; LANE_KEY_LENGTH];
249    out.copy_from_slice(&okm);
250    Ok(out)
251}
252
253#[cfg(test)]
254mod tests {
255    use super::*;
256
257    #[test]
258    fn test_human_agency_verification() {
259        // Use a static 32-byte secret for the test to avoid pulling in rand_core
260        let secret = [42u8; 32];
261        let signing_key = SigningKey::from_bytes(&secret);
262        let verifying_key: VerifyingKey = signing_key.verifying_key();
263
264        let author_did_alice = 1001;
265        let author_did_bob = 2002;
266
267        let mut frame = [NQuin {
268            subject: 0,
269            predicate: 0,
270            object: 0,
271            context: 0,
272            metadata: 0,
273            parity: 0,
274        }; 10];
275
276        // Alice's claims
277        frame[0].context = author_did_alice;
278        frame[0].subject = 55;
279
280        frame[1].context = author_did_alice;
281        frame[1].subject = 66;
282
283        // Bob's claims (injected into the same bilateral frame)
284        frame[2].context = author_did_bob;
285        frame[2].subject = 99;
286
287        // 1. Alice computes her scoped root and signs it
288        let alice_root = compute_scoped_merkle_root(&frame, author_did_alice);
289        let alice_sig = sign_agency_root(&signing_key, &alice_root);
290
291        // 2. Verification Gate validates Alice's signature successfully
292        assert_eq!(
293            verify_human_agency(&frame, author_did_alice, &verifying_key, &alice_sig),
294            Ok(())
295        );
296
297        // 3. Tampering simulation: Someone alters Alice's claim
298        frame[0].subject = 999;
299        assert_eq!(
300            verify_human_agency(&frame, author_did_alice, &verifying_key, &alice_sig),
301            Err(AgencyError::InvalidSignature)
302        );
303    }
304
305    #[test]
306    fn test_human_agency_pq_and_dual_verification() {
307        use crate::crypto::network::dual_sign::DualProof;
308        use crate::crypto::network::mldsa::generate_keypair;
309        use crate::crypto::network::types::{ED25519_SIG_LEN, ML_DSA_65_SIG_LEN};
310
311        let author_did_alice = 5001;
312        let mut frame = [NQuin {
313            subject: 42,
314            predicate: 100,
315            object: 200,
316            context: author_did_alice,
317            metadata: 0,
318            parity: 0,
319        }; 4];
320
321        let (mldsa_sk, mldsa_pk) = generate_keypair().unwrap();
322        let ed_seed = [99u8; 32];
323        let ed_signing = SigningKey::from_bytes(&ed_seed);
324        let ed_pk_bytes: [u8; 32] = ed_signing.verifying_key().to_bytes();
325
326        let alice_root = compute_scoped_merkle_root(&frame, author_did_alice);
327
328        // 1. Post-Quantum ML-DSA-65 test
329        let mut pq_sig = [0u8; ML_DSA_65_SIG_LEN];
330        sign_agency_root_pq(&mldsa_sk, &alice_root, &mut pq_sig).unwrap();
331        assert_eq!(
332            verify_human_agency_pq(&frame, author_did_alice, &mldsa_pk, &pq_sig),
333            Ok(())
334        );
335
336        // 2. Hybrid DualProof test
337        let mut dual_proof = DualProof {
338            mldsa_sig: [0u8; ML_DSA_65_SIG_LEN],
339            ed25519_sig: [0u8; ED25519_SIG_LEN],
340        };
341        sign_agency_root_dual(&mldsa_sk, &ed_seed, &alice_root, &mut dual_proof).unwrap();
342        assert_eq!(
343            verify_human_agency_dual(
344                &frame,
345                author_did_alice,
346                &ed_pk_bytes,
347                &mldsa_pk,
348                &dual_proof
349            ),
350            Ok(())
351        );
352
353        // 3. Tampering detection
354        frame[0].subject = 9999;
355        assert_eq!(
356            verify_human_agency_pq(&frame, author_did_alice, &mldsa_pk, &pq_sig),
357            Err(AgencyError::InvalidSignature)
358        );
359        assert_eq!(
360            verify_human_agency_dual(
361                &frame,
362                author_did_alice,
363                &ed_pk_bytes,
364                &mldsa_pk,
365                &dual_proof
366            ),
367            Err(AgencyError::InvalidSignature)
368        );
369    }
370
371    #[cfg(all(feature = "sanctuary-crypto", not(target_arch = "wasm32")))]
372    #[test]
373    fn derive_lane_key_is_deterministic_and_salt_bound() {
374        let pin = "1234";
375        let salt_a = b"sanctuary";
376        let salt_b = b"decoy";
377
378        let key_a1 = derive_lane_key(pin, salt_a);
379        let key_a2 = derive_lane_key(pin, salt_a);
380        let key_b = derive_lane_key(pin, salt_b);
381        let key_c = derive_lane_key("4321", salt_a);
382
383        assert_eq!(key_a1, key_a2);
384        assert_ne!(key_a1, key_b);
385        assert_ne!(key_a1, key_c);
386        assert_eq!(
387            key_a1,
388            crate::sanctuary_crypto::derive_lane_cipher_key(
389                pin.as_bytes(),
390                salt_a,
391                crate::sanctuary_crypto::DEFAULT_PBKDF2_ITERATIONS,
392            )
393        );
394    }
395}