Skip to main content

qualia_core_db/crypto/network/
secret_lease.rs

1//! Explicit zeroizing secret leases. Secrets are not Copy.
2
3use super::errors::CryptoError;
4use super::types::KeyPurpose;
5use zeroize::Zeroize;
6
7pub const SECRET_LEASE_BYTES: usize = 64;
8
9pub struct SecretLease {
10    bytes: [u8; SECRET_LEASE_BYTES],
11    len: u8,
12    purpose: KeyPurpose,
13    live: bool,
14}
15
16impl SecretLease {
17    /// Leases `secret` for `purpose`.
18    pub fn new(purpose: KeyPurpose, secret: &[u8]) -> Result<Self, CryptoError> {
19        if secret.len() > SECRET_LEASE_BYTES {
20            return Err(CryptoError::Capacity);
21        }
22        let mut bytes = [0u8; SECRET_LEASE_BYTES];
23        bytes[..secret.len()].copy_from_slice(secret);
24        Ok(Self {
25            bytes,
26            len: secret.len() as u8,
27            purpose,
28            live: true,
29        })
30    }
31
32    /// The lease purpose.
33    pub fn purpose(&self) -> Result<KeyPurpose, CryptoError> {
34        if !self.live {
35            return Err(CryptoError::Revoked);
36        }
37        Ok(self.purpose)
38    }
39
40    /// Exposes the secret only when `expected` matches the lease purpose.
41    pub fn expose(&self, expected: KeyPurpose) -> Result<&[u8], CryptoError> {
42        if !self.live {
43            return Err(CryptoError::Revoked);
44        }
45        if self.purpose != expected {
46            return Err(CryptoError::Unauthorized);
47        }
48        Ok(&self.bytes[..self.len as usize])
49    }
50
51    /// Zeroizes the leased secret.
52    pub fn destroy(&mut self) {
53        self.live = false;
54        self.bytes.zeroize();
55        self.len = 0;
56    }
57}
58
59impl Drop for SecretLease {
60    fn drop(&mut self) {
61        self.bytes.zeroize();
62    }
63}
64
65impl core::fmt::Debug for SecretLease {
66    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
67        f.debug_struct("SecretLease")
68            .field("purpose", &self.purpose)
69            .field("live", &self.live)
70            .finish()
71    }
72}
73
74#[cfg(test)]
75mod tests {
76    use super::*;
77
78    #[test]
79    fn wrong_purpose_is_unauthorized() {
80        let lease = SecretLease::new(KeyPurpose::QLinkAead, &[1u8; 32]).unwrap();
81        assert_eq!(
82            lease.expose(KeyPurpose::QSessionAead).unwrap_err(),
83            CryptoError::Unauthorized
84        );
85    }
86
87    #[test]
88    fn destroy_rejects_later_use() {
89        let mut lease = SecretLease::new(KeyPurpose::QLinkAead, &[1u8; 32]).unwrap();
90        lease.destroy();
91        assert_eq!(
92            lease.expose(KeyPurpose::QLinkAead).unwrap_err(),
93            CryptoError::Revoked
94        );
95    }
96}