Skip to main content

qualia_core_db/identity/
key_vault.rs

1use ed25519_dalek::{Signature, Signer, SigningKey, Verifier, VerifyingKey};
2use sha2::{Digest, Sha256};
3use std::fs;
4use std::path::Path;
5#[cfg(windows)]
6mod native_secure_lock;
7
8fn generate_master_secret() -> Result<[u8; 32], String> {
9    let mut secret = [0u8; 32];
10    getrandom::fill(&mut secret).map_err(|e| format!("OS RNG failed: {e}"))?;
11    Ok(secret)
12}
13
14#[cfg(all(not(target_arch = "wasm32"), not(test)))]
15fn keyring_entry_for(storage_dir: &str) -> Result<keyring::Entry, String> {
16    let mut hasher = Sha256::new();
17    hasher.update(storage_dir.as_bytes());
18    let digest = hasher.finalize();
19    let username = format!("master_{}", hex::encode(&digest[..8]));
20    keyring::Entry::new("qualia_db", &username).map_err(|e| format!("Keyring error: {e}"))
21}
22#[cfg(all(not(target_arch = "wasm32"), test))]
23fn keyring_entry_for(_storage_dir: &str) -> Result<keyring::Entry, String> {
24    Err("OS credentials are unavailable to isolated unit-test vault fixtures".into())
25}
26
27/// Closed v1 `idf:keyRole` values for purpose-separated vault material.
28///
29/// Unknown roles stay held / not-yet — never map to other-id / who.
30/// `Mixnet` is Nym client identity seed; it MUST NOT collapse into
31/// `SessionAuthentication` (or pack-publish / transport AEAD).
32#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
33#[serde(rename_all = "kebab-case")]
34pub enum KeyRole {
35    ControllerSigning,
36    RouteUpdate,
37    SessionAuthentication,
38    TransportAead,
39    QlinkEphemeralDh,
40    CapabilityPresentation,
41    DiscoveryPsk,
42    GroupDiscovery,
43    PackPublish,
44    /// Nym mixnet client identity — purpose-separated from session-authentication.
45    Mixnet,
46}
47
48impl KeyRole {
49    /// Wire / UI id (`mixnet`, `session-authentication`, …).
50    pub fn as_str(self) -> &'static str {
51        match self {
52            Self::ControllerSigning => "controller-signing",
53            Self::RouteUpdate => "route-update",
54            Self::SessionAuthentication => "session-authentication",
55            Self::TransportAead => "transport-aead",
56            Self::QlinkEphemeralDh => "qlink-ephemeral-dh",
57            Self::CapabilityPresentation => "capability-presentation",
58            Self::DiscoveryPsk => "discovery-psk",
59            Self::GroupDiscovery => "group-discovery",
60            Self::PackPublish => "pack-publish",
61            Self::Mixnet => "mixnet",
62        }
63    }
64
65    /// Parse a closed-v1 role id. Unknown → None (held / not-yet).
66    pub fn parse(s: &str) -> Option<Self> {
67        match s.trim().to_ascii_lowercase().as_str() {
68            "controller-signing" => Some(Self::ControllerSigning),
69            "route-update" => Some(Self::RouteUpdate),
70            "session-authentication" => Some(Self::SessionAuthentication),
71            "transport-aead" => Some(Self::TransportAead),
72            "qlink-ephemeral-dh" => Some(Self::QlinkEphemeralDh),
73            "capability-presentation" => Some(Self::CapabilityPresentation),
74            "discovery-psk" => Some(Self::DiscoveryPsk),
75            "group-discovery" => Some(Self::GroupDiscovery),
76            "pack-publish" => Some(Self::PackPublish),
77            "mixnet" => Some(Self::Mixnet),
78            _ => None,
79        }
80    }
81
82    /// HKDF / derive_key context — stable, purpose-tagged, never shared across roles.
83    pub fn vault_context(self) -> &'static str {
84        match self {
85            Self::ControllerSigning => "idf:keyRole:controller-signing:v1",
86            Self::RouteUpdate => "idf:keyRole:route-update:v1",
87            Self::SessionAuthentication => "idf:keyRole:session-authentication:v1",
88            Self::TransportAead => "idf:keyRole:transport-aead:v1",
89            Self::QlinkEphemeralDh => "idf:keyRole:qlink-ephemeral-dh:v1",
90            Self::CapabilityPresentation => "idf:keyRole:capability-presentation:v1",
91            Self::DiscoveryPsk => "idf:keyRole:discovery-psk:v1",
92            Self::GroupDiscovery => "idf:keyRole:group-discovery:v1",
93            Self::PackPublish => "idf:keyRole:pack-publish:v1",
94            Self::Mixnet => "idf:keyRole:mixnet:v1",
95        }
96    }
97
98    /// Closed v1 inventory (inference namespace + mixnet + pack-publish).
99    pub fn closed_v1() -> &'static [KeyRole] {
100        &[
101            Self::ControllerSigning,
102            Self::RouteUpdate,
103            Self::SessionAuthentication,
104            Self::TransportAead,
105            Self::QlinkEphemeralDh,
106            Self::CapabilityPresentation,
107            Self::DiscoveryPsk,
108            Self::GroupDiscovery,
109            Self::PackPublish,
110            Self::Mixnet,
111        ]
112    }
113}
114
115/// High-level Key Management module for the Qualia Node.
116pub struct KeyVault {
117    master_key: Option<SigningKey>,
118    storage_dir: Option<String>,
119    native_secure: bool,
120}
121
122impl KeyVault {
123    /// Native operator vault. Uses the OS credential store exclusively: no
124    /// plaintext keystore, auto-generation on read failure or legacy fallback.
125    /// `create` must follow an explicit native operator create gesture.
126    #[cfg(all(windows, not(test)))]
127    pub fn open_native_secure(storage_dir: &str, create: bool) -> Result<Self, String> {
128        if storage_dir.is_empty() || storage_dir.len() > 4096 {
129            return Err("native secure vault requires bounded profile path".into());
130        }
131        let (profile_path, _profile_lock) =
132            native_secure_lock::acquire(Path::new(storage_dir), create)?;
133        if profile_path.join("keystore.bin").exists() {
134            return Err("legacy plaintext vault requires explicit protected migration".into());
135        }
136        // Build directly from the concrete OS store. A replaceable global default
137        // (including test/mock stores) cannot supply production enrollment keys.
138        use keyring_core::api::CredentialStoreApi;
139        let store = windows_native_keyring_store::Store::new()
140            .map_err(|e| format!("Windows Credential Manager unavailable: {e}"))?;
141        let mut hasher = Sha256::new();
142        hasher.update(profile_path.to_string_lossy().as_bytes());
143        let profile = format!("native_{}", hex::encode(hasher.finalize()));
144        let modifiers = std::collections::HashMap::from([("persistence", "Local")]);
145        let entry = store
146            .build("qualia_native_authoring_v1", &profile, Some(&modifiers))
147            .map_err(|e| format!("native OS credential construction: {e}"))?;
148        let mut secret = zeroize::Zeroizing::new([0u8; 32]);
149        match entry.get_password() {
150            Ok(encoded) => {
151                if create {
152                    return Err("native secure vault already exists".into());
153                }
154                let encoded = zeroize::Zeroizing::new(encoded);
155                hex::decode_to_slice(encoded.as_str(), secret.as_mut())
156                    .map_err(|_| "invalid OS credential vault key")?;
157            }
158            Err(keyring_core::Error::NoEntry) if create => {
159                *secret = generate_master_secret()?;
160                let encoded = zeroize::Zeroizing::new(hex::encode(secret.as_ref()));
161                entry
162                    .set_password(encoded.as_str())
163                    .map_err(|e| format!("OS credential write failed: {e}"))?;
164                let verified = zeroize::Zeroizing::new(
165                    entry
166                        .get_password()
167                        .map_err(|e| format!("OS credential readback failed: {e}"))?,
168                );
169                if verified.as_str() != encoded.as_str() {
170                    return Err("OS credential readback mismatch".into());
171                }
172            }
173            Err(e) => return Err(format!("native secure vault unavailable: {e}")),
174        }
175        if *secret == [0; 32] {
176            return Err("empty native secure vault key".into());
177        }
178        if entry
179            .get_attributes()
180            .map_err(|e| format!("OS credential persistence unavailable: {e}"))?
181            .get("persistence")
182            .is_none_or(|p| p != "Local")
183        {
184            return Err("native enrollment requires OS Local persistence".into());
185        }
186        // No generic unlock fallback: secure callers reopen this explicit method.
187        Ok(Self {
188            master_key: Some(SigningKey::from_bytes(&secret)),
189            storage_dir: None,
190            native_secure: true,
191        })
192    }
193    #[cfg(all(not(target_arch = "wasm32"), not(windows), not(test)))]
194    pub fn open_native_secure(_storage_dir: &str, _create: bool) -> Result<Self, String> {
195        Err("native enrollment OS credential backend is not qualified on this target".into())
196    }
197    #[cfg(all(not(target_arch = "wasm32"), test))]
198    pub fn open_native_secure(_storage_dir: &str, _create: bool) -> Result<Self, String> {
199        Err("OS credential operations are explicitly disabled in unit tests".into())
200    }
201    pub fn is_native_secure(&self) -> bool {
202        self.native_secure
203    }
204    /// Creates an in-memory KeyVault with a fresh ephemeral key (for tests/stubs only).
205    pub fn new() -> Self {
206        use sha2::{Digest, Sha256};
207        let mut hasher = Sha256::new();
208        hasher.update(b"ephemeral");
209        let result = hasher.finalize();
210        let mut secret = [0u8; 32];
211        secret.copy_from_slice(&result);
212        Self {
213            master_key: Some(SigningKey::from_bytes(&secret)),
214            storage_dir: None,
215            native_secure: false,
216        }
217    }
218
219    /// `true` when `locked`.
220    pub fn is_locked(&self) -> bool {
221        self.master_key.is_none()
222    }
223
224    /// Locks the vault.
225    pub fn lock(&mut self) {
226        self.master_key = None;
227    }
228
229    #[cfg(not(target_arch = "wasm32"))]
230    /// Unlocks the vault.
231    pub fn unlock(&mut self) -> Result<(), String> {
232        let dir = self
233            .storage_dir
234            .as_ref()
235            .ok_or("No storage dir configured")?;
236        let temp = Self::load_or_generate(dir)?;
237        self.master_key = temp.master_key;
238        Ok(())
239    }
240
241    #[cfg(target_arch = "wasm32")]
242    /// Unlocks the vault.
243    pub fn unlock(&mut self) -> Result<(), String> {
244        let temp = Self::load_or_generate("")?;
245        self.master_key = temp.master_key;
246        Ok(())
247    }
248
249    #[cfg(not(target_arch = "wasm32"))]
250    /// Loads an existing vault or generates one.
251    pub fn load_or_generate(storage_dir: &str) -> Result<Self, String> {
252        let vault_path = Path::new(storage_dir).join("keystore.bin");
253        let entry = keyring_entry_for(storage_dir).ok();
254
255        let master_key = match entry.as_ref().and_then(|e| e.get_password().ok()) {
256            Some(secret_hex) => {
257                let bytes =
258                    hex::decode(secret_hex).map_err(|e| format!("Invalid hex in keyring: {e}"))?;
259                if bytes.len() != 32 {
260                    return Err("Corrupted master key length in keyring".into());
261                }
262                let mut secret = [0u8; 32];
263                secret.copy_from_slice(&bytes[0..32]);
264                SigningKey::from_bytes(&secret)
265            }
266            None => {
267                if vault_path.exists() {
268                    let bytes = fs::read(&vault_path)
269                        .map_err(|e| format!("Failed to read keystore: {e}"))?;
270                    if bytes.len() != 32 {
271                        return Err("Corrupted master key length".into());
272                    }
273                    let secret_hex = hex::encode(&bytes[0..32]);
274                    if let Some(ref entry) = entry {
275                        let _ = entry.set_password(&secret_hex);
276                    }
277                    let mut secret = [0u8; 32];
278                    secret.copy_from_slice(&bytes[0..32]);
279                    SigningKey::from_bytes(&secret)
280                } else {
281                    let secret = generate_master_secret()?;
282                    let new_key = SigningKey::from_bytes(&secret);
283                    let secret_hex = hex::encode(secret);
284                    if let Some(ref entry) = entry {
285                        let _ = entry.set_password(&secret_hex);
286                    }
287                    if let Some(parent) = vault_path.parent() {
288                        if !parent.as_os_str().is_empty() {
289                            fs::create_dir_all(parent)
290                                .map_err(|e| format!("Failed to create keystore dir: {e}"))?;
291                        }
292                    }
293                    fs::write(&vault_path, secret)
294                        .map_err(|e| format!("Failed to write keystore: {e}"))?;
295                    new_key
296                }
297            }
298        };
299
300        Ok(Self {
301            master_key: Some(master_key),
302            storage_dir: Some(storage_dir.to_string()),
303            native_secure: false,
304        })
305    }
306
307    #[cfg(target_arch = "wasm32")]
308    /// Loads an existing vault or generates one.
309    pub fn load_or_generate(storage_dir: &str) -> Result<Self, String> {
310        let vault_path = Path::new(storage_dir).join("keystore.bin");
311
312        let master_key = if vault_path.exists() {
313            let bytes =
314                fs::read(&vault_path).map_err(|e| format!("Failed to read keystore: {}", e))?;
315            if bytes.len() != 32 {
316                return Err("Corrupted master key length".into());
317            }
318            let mut secret = [0u8; 32];
319            secret.copy_from_slice(&bytes[0..32]);
320            SigningKey::from_bytes(&secret)
321        } else {
322            let secret = generate_master_secret()?;
323            if let Some(parent) = vault_path.parent() {
324                if !parent.as_os_str().is_empty() {
325                    fs::create_dir_all(parent)
326                        .map_err(|e| format!("Failed to create keystore dir: {e}"))?;
327                }
328            }
329            if !storage_dir.is_empty() {
330                fs::write(&vault_path, secret)
331                    .map_err(|e| format!("Failed to write keystore: {e}"))?;
332            }
333            SigningKey::from_bytes(&secret)
334        };
335
336        Ok(Self {
337            master_key: Some(master_key),
338            storage_dir: Some(storage_dir.to_string()),
339            native_secure: false,
340        })
341    }
342
343    /// Derives a deterministic Pairwise or Front Door key from the Master Key.
344    /// This ensures we can recover all DIDs from the single master root.
345    pub fn derive_key(&self, context_id: &str) -> SigningKey {
346        let master_key = self.master_key.as_ref().expect("Vault is locked");
347        let mut hasher = Sha256::new();
348        hasher.update(master_key.to_bytes());
349        hasher.update(context_id.as_bytes());
350        let result = hasher.finalize();
351
352        let mut child_secret = [0u8; 32];
353        child_secret.copy_from_slice(&result);
354        SigningKey::from_bytes(&child_secret)
355    }
356
357    /// Purpose-separated child key for a closed `KeyRole`.
358    ///
359    /// Host paths request this (or [`Self::request_role_seed`]) at use-time.
360    /// Agents never hold the returned material — only the vault does.
361    pub fn derive_key_for_role(&self, role: KeyRole) -> SigningKey {
362        self.derive_key(role.vault_context())
363    }
364
365    /// Request 32-byte seed for `role` (host-only). Never log or put in Quins.
366    ///
367    /// Returns Err when the vault is locked. Callers must zeroize after use
368    /// when the seed is no longer needed for the active operation.
369    pub fn request_role_seed(&self, role: KeyRole) -> Result<[u8; 32], String> {
370        if self.is_locked() {
371            return Err(format!(
372                "KeyVault locked — cannot release keyRole {}",
373                role.as_str()
374            ));
375        }
376        Ok(self.derive_key_for_role(role).to_bytes())
377    }
378
379    /// Agent-facing grant: purpose metadata only — never key material.
380    pub fn agent_request_role(&self, role: KeyRole) -> KeyRoleGrant {
381        KeyRoleGrant {
382            role: role.as_str().to_string(),
383            holder: "keyvault".into(),
384            vault_locked: self.is_locked(),
385            purpose: role.vault_context().to_string(),
386            material_held_by_agent: false,
387        }
388    }
389
390    /// Computes an Ed25519 signature over a generic byte payload
391    pub fn sign_payload(&self, signing_key: &SigningKey, payload: &[u8]) -> Signature {
392        signing_key.sign(payload)
393    }
394
395    /// Exposes the raw bytes of the master key for libp2p identity bindings
396    pub fn get_master_key_bytes(&self) -> [u8; 32] {
397        self.master_key
398            .as_ref()
399            .expect("Vault is locked")
400            .to_bytes()
401    }
402
403    /// Ed25519 verifying key bytes for a context-derived pairwise key.
404    pub fn public_key_bytes_for_context(&self, context_id: &str) -> [u8; 32] {
405        VerifyingKey::from(&self.derive_key(context_id)).to_bytes()
406    }
407
408    /// Verifies a payload against a given public key bytes
409    pub fn verify_signature(
410        public_key_bytes: &[u8; 32],
411        payload: &[u8],
412        signature_bytes: &[u8; 64],
413    ) -> Result<(), String> {
414        let verifying_key =
415            VerifyingKey::from_bytes(public_key_bytes).map_err(|_| "Invalid public key")?;
416        let signature = Signature::from_bytes(signature_bytes);
417
418        verifying_key
419            .verify(payload, &signature)
420            .map_err(|_| "Invalid signature".to_string())
421    }
422
423    /// Generates a WebID-TLS / mTLS compatible self-signed X.509 certificate.
424    ///
425    /// The DID URI is placed in the Subject Alternative Name URI extension so
426    /// transport identity can be bound to the Qualia principal. Uses real `rcgen`
427    /// PEM output (not a mock). Private key material is the provided Ed25519 seed
428    /// encoded as PKCS#8 PEM.
429    pub fn generate_webid_tls_cert(
430        &self,
431        key: &SigningKey,
432        did_uri: &str,
433    ) -> Result<(String, String), String> {
434        generate_webid_tls_cert_for_seed(&key.to_bytes(), did_uri)
435    }
436}
437
438/// PKCS#8 PEM + self-signed cert for an Ed25519 seed and DID SAN URI.
439pub fn generate_webid_tls_cert_for_seed(
440    seed: &[u8; 32],
441    did_uri: &str,
442) -> Result<(String, String), String> {
443    use rcgen::{
444        CertificateParams, DnType, ExtendedKeyUsagePurpose, IsCa, KeyPair, KeyUsagePurpose, SanType,
445    };
446
447    if did_uri.trim().is_empty() {
448        return Err("did_uri must not be empty".into());
449    }
450
451    let key_pem = format_ed25519_pkcs8_pem(seed);
452    let key_pair =
453        KeyPair::from_pem(&key_pem).map_err(|e| format!("rcgen KeyPair::from_pem: {e}"))?;
454
455    let mut params =
456        CertificateParams::new(Vec::<String>::new()).map_err(|e| format!("cert params: {e}"))?;
457    params.distinguished_name.push(DnType::CommonName, did_uri);
458    params.subject_alt_names = vec![SanType::URI(
459        did_uri.try_into().map_err(|e| format!("SAN URI: {e}"))?,
460    )];
461    params.is_ca = IsCa::NoCa;
462    params.key_usages = vec![
463        KeyUsagePurpose::DigitalSignature,
464        KeyUsagePurpose::KeyEncipherment,
465    ];
466    params.extended_key_usages = vec![
467        ExtendedKeyUsagePurpose::ClientAuth,
468        ExtendedKeyUsagePurpose::ServerAuth,
469    ];
470
471    let cert = params
472        .self_signed(&key_pair)
473        .map_err(|e| format!("self_signed: {e}"))?;
474    Ok((cert.pem(), key_pair.serialize_pem()))
475}
476
477#[cfg(test)]
478mod webid_tls_tests {
479    use super::*;
480
481    #[test]
482    fn webid_tls_cert_is_real_pem_with_did_san() {
483        let seed = [9u8; 32];
484        let did = "did:q42:person:aabbccddeeff00112233445566778899aabbccddeeff00112233445566778899";
485        let (cert, key) = generate_webid_tls_cert_for_seed(&seed, did).expect("cert");
486        assert!(cert.contains("BEGIN CERTIFICATE"));
487        assert!(key.contains("BEGIN PRIVATE KEY") || key.contains("BEGIN"));
488        assert!(!cert.contains("MIIMOCK"));
489    }
490}
491
492/// RFC 8410 PKCS#8 for an Ed25519 private key seed (32 bytes).
493fn format_ed25519_pkcs8_pem(seed: &[u8; 32]) -> String {
494    // PrivateKeyInfo ::= SEQUENCE {
495    //   version                   Version, -- 0
496    //   privateKeyAlgorithm       AlgorithmIdentifier, -- id-Ed25519
497    //   privateKey                OCTET STRING, -- OCTET STRING of 32-byte seed
498    // }
499    let mut inner_octet = Vec::with_capacity(2 + 32);
500    inner_octet.push(0x04); // OCTET STRING
501    inner_octet.push(32);
502    inner_octet.extend_from_slice(seed);
503
504    let mut body = Vec::new();
505    // version INTEGER 0
506    body.extend_from_slice(&[0x02, 0x01, 0x00]);
507    // AlgorithmIdentifier SEQUENCE { OID 1.3.101.112 }
508    body.extend_from_slice(&[0x30, 0x05, 0x06, 0x03, 0x2b, 0x65, 0x70]);
509    // privateKey OCTET STRING wrapping inner OCTET STRING
510    body.push(0x04);
511    body.push(inner_octet.len() as u8);
512    body.extend_from_slice(&inner_octet);
513
514    let mut der = Vec::new();
515    der.push(0x30);
516    der.push(body.len() as u8);
517    der.extend_from_slice(&body);
518
519    use base64::Engine as _;
520    let b64 = base64::engine::general_purpose::STANDARD.encode(&der);
521    let mut pem = String::from("-----BEGIN PRIVATE KEY-----\n");
522    for chunk in b64.as_bytes().chunks(64) {
523        pem.push_str(std::str::from_utf8(chunk).unwrap_or(""));
524        pem.push('\n');
525    }
526    pem.push_str("-----END PRIVATE KEY-----\n");
527    pem
528}
529
530impl KeyVault {
531    /// Issues a cryptographically signed Semantic Token for an installed qapp.
532    /// The token enforces gatekeeper boundary policies (which shapes the qapp can access).
533    pub fn issue_qapp_token(
534        &self,
535        qapp_did: &str,
536        audience: &str,
537        expiry_epoch: u64,
538        nonce: &str,
539        capabilities: Vec<String>,
540        sensitivity_clearance: SubgraphLayer,
541    ) -> Result<String, String> {
542        let payload = QappSessionTokenV2 {
543            qapp_did: qapp_did.to_string(),
544            expiry_epoch,
545            audience: audience.to_string(),
546            nonce: nonce.to_string(),
547            capabilities,
548            sensitivity_clearance,
549        };
550        let payload_json =
551            serde_json::to_string(&payload).map_err(|e| format!("Serialization error: {}", e))?;
552
553        let master_key = self.master_key.as_ref().expect("Vault is locked");
554        let signature = self.sign_payload(master_key, payload_json.as_bytes());
555        let signature_hex = hex::encode(signature.to_bytes());
556        let payload_hex = hex::encode(payload_json.as_bytes());
557
558        // Token format: payload_hex.signature_hex
559        Ok(format!("{}.{}", payload_hex, signature_hex))
560    }
561
562    /// Verifies a qapp token's signature using the Master Key, and checks expiry and audience.
563    pub fn verify_qapp_token(
564        &self,
565        token: &str,
566        expected_audience: &str,
567    ) -> Result<QappSessionTokenV2, String> {
568        let parts: Vec<&str> = token.split('.').collect();
569        if parts.len() != 2 {
570            return Err("Invalid semantic token format".into());
571        }
572
573        let payload_bytes =
574            hex::decode(parts[0]).map_err(|_| "Invalid payload hex representation".to_string())?;
575        let signature_bytes = hex::decode(parts[1])
576            .map_err(|_| "Invalid signature hex representation".to_string())?;
577
578        if signature_bytes.len() != 64 {
579            return Err("Invalid signature byte length".into());
580        }
581        let mut sig_array = [0u8; 64];
582        sig_array.copy_from_slice(&signature_bytes);
583
584        let master_key = self.master_key.as_ref().expect("Vault is locked");
585        let verifying_key = VerifyingKey::from(master_key);
586        let signature = Signature::from_bytes(&sig_array);
587        verifying_key
588            .verify(&payload_bytes, &signature)
589            .map_err(|_| "Invalid token signature".to_string())?;
590
591        let payload: QappSessionTokenV2 = serde_json::from_slice(&payload_bytes)
592            .map_err(|e| format!("Failed to parse token payload: {}", e))?;
593
594        let now = std::time::SystemTime::now()
595            .duration_since(std::time::UNIX_EPOCH)
596            .map_err(|_| "Time went backwards")?
597            .as_secs();
598
599        if payload.expiry_epoch < now {
600            return Err("Token expired".into());
601        }
602
603        if payload.audience != expected_audience {
604            return Err("Token audience mismatch".into());
605        }
606
607        Ok(payload)
608    }
609}
610
611/// Agent-visible ticket for a keyRole request. Never carries secret bytes.
612#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, PartialEq, Eq)]
613pub struct KeyRoleGrant {
614    pub role: String,
615    pub holder: String,
616    pub vault_locked: bool,
617    pub purpose: String,
618    /// Always false — agents request, never hold.
619    pub material_held_by_agent: bool,
620}
621
622#[derive(serde::Serialize, serde::Deserialize, Clone, Debug)]
623pub struct QappSessionTokenV2 {
624    pub qapp_did: String,
625    pub expiry_epoch: u64,
626    pub audience: String,
627    pub nonce: String,
628    pub capabilities: Vec<String>,
629    pub sensitivity_clearance: SubgraphLayer,
630}
631
632// ── Credential-gated subgraph layer encryption ───────────────────────────────
633
634/// Named sensitivity tiers for credential-gated subgraph views.
635///
636/// Each layer has a dedicated AES-256-GCM key derived from the node's master key.
637/// Access is gated by the deontic engine evaluating the agent's VCs against the
638/// layer's ODRL policy before releasing the key.
639#[derive(
640    serde::Serialize, serde::Deserialize, Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord,
641)]
642#[repr(u8)]
643pub enum SubgraphLayer {
644    Public = 0,
645    Professional = 1,
646    Legal = 2,
647    Medical = 3,
648    Fiduciary = 4,
649}
650
651impl SubgraphLayer {
652    /// HKDF info label used for key derivation — must stay stable across versions.
653    pub fn label(self) -> &'static str {
654        match self {
655            Self::Public => "qualia:subgraph:layer:public",
656            Self::Professional => "qualia:subgraph:layer:professional",
657            Self::Legal => "qualia:subgraph:layer:legal",
658            Self::Medical => "qualia:subgraph:layer:medical",
659            Self::Fiduciary => "qualia:subgraph:layer:fiduciary",
660        }
661    }
662
663    /// Minimum sensitivity metadata bits\[59:56\] required to reach this layer.
664    pub fn sensitivity_tier(self) -> u8 {
665        self as u8
666    }
667}
668
669/// A 32-byte AES-256-GCM subgraph key bound to a specific `SubgraphLayer`.
670pub struct SubgraphKey {
671    layer: SubgraphLayer,
672    key_bytes: [u8; 32],
673}
674
675impl std::fmt::Debug for SubgraphKey {
676    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
677        f.debug_struct("SubgraphKey")
678            .field("layer", &self.layer)
679            .field("key_bytes", &"[REDACTED]")
680            .finish()
681    }
682}
683
684impl zeroize::Zeroize for SubgraphKey {
685    fn zeroize(&mut self) {
686        self.key_bytes.zeroize();
687    }
688}
689
690impl Drop for SubgraphKey {
691    fn drop(&mut self) {
692        use zeroize::Zeroize;
693        self.key_bytes.zeroize();
694    }
695}
696
697impl SubgraphKey {
698    /// Raw key bytes — use only to pass to an AES-GCM cipher; do not persist unencrypted.
699    #[inline]
700    pub fn raw(&self) -> &[u8; 32] {
701        &self.key_bytes
702    }
703
704    /// Subgraph layer.
705    pub fn layer(&self) -> SubgraphLayer {
706        self.layer
707    }
708}
709
710/// An X25519 ECDH-encapsulated subgraph key (key wrapped for a specific recipient DID).
711///
712/// `ephemeral_public` is the sender's ephemeral X25519 public key (32 bytes).
713/// `ciphertext` is the 32-byte layer key XOR-masked with the ECDH shared secret.
714///
715/// The recipient computes `shared = X25519(their_static_private, ephemeral_public)`,
716/// then `layer_key = ciphertext XOR shared`, then verifies with `mac`.
717#[derive(Debug, Clone)]
718pub struct EncapsulatedKey {
719    pub layer: SubgraphLayer,
720    pub ephemeral_public: [u8; 32],
721    /// `AES-256-GCM ciphertext` of the 32-byte layer key (32 + 16-byte tag = 48 bytes).
722    pub ciphertext: [u8; 48],
723    /// Nonce used for the AES-GCM wrap (12 bytes).
724    pub nonce: [u8; 12],
725}
726
727impl KeyVault {
728    /// Derive a deterministic AES-256-GCM key for `layer` using HKDF-SHA-256.
729    ///
730    /// IKM  = master ed25519 secret key bytes (32 bytes)
731    /// Salt = b"qualia:subgraph:salt:v1"
732    /// Info = `layer.label()` bytes
733    pub fn generate_layer_key(&self, layer: SubgraphLayer) -> SubgraphKey {
734        use hkdf::Hkdf;
735        use sha2::Sha256;
736
737        let master_key = self.master_key.as_ref().expect("Vault is locked");
738        let ikm = master_key.to_bytes();
739        let salt: &[u8] = b"qualia:subgraph:salt:v1";
740        let hk = Hkdf::<Sha256>::new(Some(salt), &ikm);
741
742        let mut key_bytes = [0u8; 32];
743        hk.expand(layer.label().as_bytes(), &mut key_bytes)
744            .expect("HKDF expand: 32 bytes always fits");
745
746        SubgraphKey { layer, key_bytes }
747    }
748
749    /// Encapsulate `layer_key` for a recipient identified by their X25519 public key bytes.
750    ///
751    /// Uses ephemeral X25519 ECDH + AES-256-GCM to wrap the 32-byte layer key.
752    /// The `recipient_x25519_pub` is typically derived from the recipient's DID key material.
753    ///
754    /// # Errors
755    /// Returns `Err` if the recipient public key bytes are invalid.
756    pub fn encapsulate_for_recipient(
757        &self,
758        layer_key: &SubgraphKey,
759        recipient_x25519_pub: &[u8; 32],
760        nonce_entropy: &[u8; 32],
761    ) -> Result<EncapsulatedKey, String> {
762        use aes_gcm::{aead::Aead, Aes256Gcm, KeyInit};
763        use x25519_dalek::PublicKey;
764
765        // Derive ephemeral X25519 keypair from nonce_entropy (deterministic for tests).
766        let ephemeral_scalar = {
767            let mut h = Sha256::new();
768            h.update(b"qualia:ecdh:ephemeral:");
769            h.update(nonce_entropy);
770            h.update(layer_key.layer().label().as_bytes());
771            let digest = h.finalize();
772            let mut scalar = [0u8; 32];
773            scalar.copy_from_slice(&digest);
774            scalar
775        };
776
777        // Build ephemeral static secret from the scalar bytes.
778        let ephemeral_secret = x25519_dalek::StaticSecret::from(ephemeral_scalar);
779        let ephemeral_public = PublicKey::from(&ephemeral_secret);
780
781        // ECDH shared secret.
782        let recipient_pub = PublicKey::from(*recipient_x25519_pub);
783        let shared_secret = ephemeral_secret.diffie_hellman(&recipient_pub);
784
785        // Derive AES-GCM key from ECDH shared secret via SHA-256.
786        let wrap_key_bytes = {
787            let mut h = Sha256::new();
788            h.update(shared_secret.as_bytes());
789            h.update(b":qualia:wrap:");
790            h.update(layer_key.layer().label().as_bytes());
791            h.finalize()
792        };
793
794        // Derive 12-byte AES-GCM nonce from nonce_entropy.
795        let nonce_bytes: [u8; 12] = {
796            let mut h = Sha256::new();
797            h.update(b"qualia:nonce:");
798            h.update(nonce_entropy);
799            let d = h.finalize();
800            let mut n = [0u8; 12];
801            n.copy_from_slice(&d[..12]);
802            n
803        };
804
805        let cipher =
806            Aes256Gcm::new_from_slice(&wrap_key_bytes).map_err(|_| "AES-GCM key init failed")?;
807        let aes_nonce = aes_gcm::Nonce::try_from(nonce_bytes.as_slice()).unwrap();
808
809        let ct_vec = cipher
810            .encrypt(&aes_nonce, layer_key.raw().as_ref())
811            .map_err(|_| "AES-GCM encryption failed")?;
812
813        let mut ciphertext = [0u8; 48];
814        if ct_vec.len() != 48 {
815            return Err(format!("unexpected ciphertext length {}", ct_vec.len()));
816        }
817        ciphertext.copy_from_slice(&ct_vec);
818
819        Ok(EncapsulatedKey {
820            layer: layer_key.layer(),
821            ephemeral_public: *ephemeral_public.as_bytes(),
822            ciphertext,
823            nonce: nonce_bytes,
824        })
825    }
826
827    /// Decapsulate an `EncapsulatedKey` using the recipient's X25519 static secret key bytes.
828    ///
829    /// Returns the 32-byte layer key on success.
830    pub fn decapsulate(
831        &self,
832        encapsulated: &EncapsulatedKey,
833        recipient_x25519_secret: &[u8; 32],
834    ) -> Result<SubgraphKey, String> {
835        use aes_gcm::{aead::Aead, Aes256Gcm, KeyInit};
836        use x25519_dalek::{PublicKey, StaticSecret};
837
838        let secret = StaticSecret::from(*recipient_x25519_secret);
839        let ephemeral_pub = PublicKey::from(encapsulated.ephemeral_public);
840        let shared_secret = secret.diffie_hellman(&ephemeral_pub);
841
842        let wrap_key_bytes = {
843            let mut h = Sha256::new();
844            h.update(shared_secret.as_bytes());
845            h.update(b":qualia:wrap:");
846            h.update(encapsulated.layer.label().as_bytes());
847            h.finalize()
848        };
849
850        let cipher =
851            Aes256Gcm::new_from_slice(&wrap_key_bytes).map_err(|_| "AES-GCM key init failed")?;
852        let nonce = aes_gcm::Nonce::try_from(encapsulated.nonce.as_slice()).unwrap();
853
854        let plaintext = cipher
855            .decrypt(&nonce, encapsulated.ciphertext.as_ref())
856            .map_err(|_| "AES-GCM decryption failed — wrong key or tampered ciphertext")?;
857
858        if plaintext.len() != 32 {
859            return Err(format!("unexpected plaintext length {}", plaintext.len()));
860        }
861        let mut key_bytes = [0u8; 32];
862        key_bytes.copy_from_slice(&plaintext);
863
864        Ok(SubgraphKey {
865            layer: encapsulated.layer,
866            key_bytes,
867        })
868    }
869
870    /// Derive the X25519 static secret for this node from the master Ed25519 key.
871    ///
872    /// Used when the node itself is a VC recipient.
873    pub fn derive_x25519_secret(&self) -> [u8; 32] {
874        let master_key = self.master_key.as_ref().expect("Vault is locked");
875        let mut h = Sha256::new();
876        h.update(master_key.to_bytes());
877        h.update(b"qualia:x25519:static");
878        h.finalize().into()
879    }
880}
881
882#[cfg(test)]
883mod subgraph_key_tests {
884    use super::*;
885
886    fn test_vault() -> KeyVault {
887        let tmp = tempfile::tempdir().expect("tmpdir");
888        KeyVault::load_or_generate(tmp.path().to_str().unwrap()).expect("vault")
889    }
890
891    #[test]
892    fn layer_key_derivation_is_deterministic() {
893        let vault = test_vault();
894        let k1 = vault.generate_layer_key(SubgraphLayer::Medical);
895        let k2 = vault.generate_layer_key(SubgraphLayer::Medical);
896        assert_eq!(k1.raw(), k2.raw());
897    }
898
899    #[test]
900    fn different_layers_produce_different_keys() {
901        let vault = test_vault();
902        let med = vault.generate_layer_key(SubgraphLayer::Medical);
903        let leg = vault.generate_layer_key(SubgraphLayer::Legal);
904        let fid = vault.generate_layer_key(SubgraphLayer::Fiduciary);
905        assert_ne!(med.raw(), leg.raw());
906        assert_ne!(leg.raw(), fid.raw());
907        assert_ne!(med.raw(), fid.raw());
908    }
909
910    #[test]
911    fn encapsulate_decapsulate_roundtrip() {
912        let vault = test_vault();
913        let layer_key = vault.generate_layer_key(SubgraphLayer::Fiduciary);
914
915        // Recipient's X25519 keys.
916        let recipient_secret = vault.derive_x25519_secret();
917        let recipient_pub = {
918            use x25519_dalek::{PublicKey, StaticSecret};
919            let s = StaticSecret::from(recipient_secret);
920            *PublicKey::from(&s).as_bytes()
921        };
922
923        let nonce_entropy = [0x42u8; 32];
924        let encapsulated = vault
925            .encapsulate_for_recipient(&layer_key, &recipient_pub, &nonce_entropy)
926            .expect("encapsulate");
927
928        let recovered = vault
929            .decapsulate(&encapsulated, &recipient_secret)
930            .expect("decapsulate");
931
932        assert_eq!(recovered.raw(), layer_key.raw());
933        assert_eq!(recovered.layer(), SubgraphLayer::Fiduciary);
934    }
935
936    #[test]
937    fn lock_and_unlock_roundtrip() {
938        let tmp = tempfile::tempdir().expect("tmpdir");
939        let path = tmp.path().to_str().unwrap();
940        let mut vault = KeyVault::load_or_generate(path).expect("vault");
941        assert!(!vault.is_locked());
942
943        let before = vault.get_master_key_bytes();
944        vault.lock();
945        assert!(vault.is_locked());
946
947        vault.unlock().expect("unlock");
948        assert!(!vault.is_locked());
949        assert_eq!(vault.get_master_key_bytes(), before);
950    }
951
952    #[test]
953    fn keystore_file_fallback_roundtrip() {
954        let tmp = tempfile::tempdir().expect("tmpdir");
955        let path = tmp.path().to_str().unwrap();
956        let key_1 = {
957            let vault = KeyVault::load_or_generate(path).expect("vault");
958            vault.get_master_key_bytes()
959        };
960        // Verify keystore.bin was created on disk
961        let keystore_file = tmp.path().join("keystore.bin");
962        assert!(keystore_file.exists());
963        assert_eq!(fs::read(&keystore_file).unwrap().len(), 32);
964
965        // Load again from same directory and verify same master key
966        let key_2 = {
967            let vault = KeyVault::load_or_generate(path).expect("vault reloaded");
968            vault.get_master_key_bytes()
969        };
970        assert_eq!(key_1, key_2);
971    }
972
973    #[test]
974    fn decapsulate_wrong_key_fails() {
975        let vault = test_vault();
976        let layer_key = vault.generate_layer_key(SubgraphLayer::Legal);
977
978        let recipient_secret = vault.derive_x25519_secret();
979        let recipient_pub = {
980            use x25519_dalek::{PublicKey, StaticSecret};
981            let s = StaticSecret::from(recipient_secret);
982            *PublicKey::from(&s).as_bytes()
983        };
984
985        let nonce_entropy = [0x99u8; 32];
986        let encapsulated = vault
987            .encapsulate_for_recipient(&layer_key, &recipient_pub, &nonce_entropy)
988            .expect("encapsulate");
989
990        let wrong_secret = [0xFFu8; 32];
991        let result = vault.decapsulate(&encapsulated, &wrong_secret);
992        assert!(result.is_err());
993    }
994}
995
996#[cfg(test)]
997mod key_role_tests {
998    use super::*;
999
1000    fn test_vault() -> KeyVault {
1001        // Ephemeral vault — no OS keyring required in CI/box.
1002        KeyVault::new()
1003    }
1004
1005    #[test]
1006    fn mixnet_seed_differs_from_session_authentication() {
1007        let vault = test_vault();
1008        let mix = vault.request_role_seed(KeyRole::Mixnet).expect("mixnet");
1009        let sess = vault
1010            .request_role_seed(KeyRole::SessionAuthentication)
1011            .expect("session");
1012        assert_ne!(mix, sess);
1013        assert_ne!(
1014            KeyRole::Mixnet.vault_context(),
1015            KeyRole::SessionAuthentication.vault_context()
1016        );
1017    }
1018
1019    #[test]
1020    fn agent_request_never_holds_material() {
1021        let vault = test_vault();
1022        let g = vault.agent_request_role(KeyRole::Mixnet);
1023        assert_eq!(g.role, "mixnet");
1024        assert_eq!(g.holder.as_str(), "keyvault");
1025        assert!(!g.material_held_by_agent);
1026        assert!(!g.vault_locked);
1027    }
1028
1029    #[test]
1030    fn unknown_role_parse_is_none() {
1031        assert!(KeyRole::parse("other-id").is_none());
1032        assert_eq!(KeyRole::parse("mixnet"), Some(KeyRole::Mixnet));
1033    }
1034}