Skip to main content

hyde_core/
security_level.rs

1use std::time::Duration;
2
3/// Controls the trade-off between security and performance when accessing TEE-protected data.
4///
5/// | Level | Cached | Attack surface | Speed |
6/// |-------|--------|---------------|-------|
7/// | `Paranoid` | Nothing | Minimal | Slow (TPM every call) |
8/// | `Standard` | Data Key only | 32-byte key in memory | Fast (AES-GCM only) |
9/// | `Performance` | Data Key + plaintext | Full plaintext in memory | Fastest |
10#[derive(Debug, Clone, Copy, PartialEq, Eq)]
11pub enum SecurityLevel {
12    /// Every `unprotect()` call hits the TEE (TPM unseal + AES decrypt).
13    /// No plaintext or data key is ever cached in memory.
14    /// Slowest, but smallest attack surface.
15    Paranoid,
16
17    /// The unwrapped data key is cached in mlock'd, zeroize-on-drop memory
18    /// for a configurable TTL. The plaintext itself is never cached.
19    /// Each `unprotect()` still performs AES-GCM decryption, but avoids
20    /// the expensive TPM unseal round-trip for repeated accesses.
21    Standard {
22        /// How long to keep the unwrapped data key in memory.
23        ttl: Duration,
24    },
25
26    /// Both the unwrapped data key AND the decrypted plaintext are cached
27    /// in mlock'd, zeroize-on-drop memory for the TTL period.
28    /// Fastest for repeated reads of the same data, but the plaintext
29    /// lives in process memory until the TTL expires or the cache is flushed.
30    Performance {
31        /// How long to keep cached data in memory.
32        ttl: Duration,
33    },
34}
35
36impl SecurityLevel {
37    /// Standard level with a default TTL of 30 seconds.
38    pub fn standard() -> Self {
39        SecurityLevel::Standard {
40            ttl: Duration::from_secs(30),
41        }
42    }
43
44    /// Performance level with a default TTL of 10 seconds.
45    pub fn performance() -> Self {
46        SecurityLevel::Performance {
47            ttl: Duration::from_secs(10),
48        }
49    }
50
51    /// Returns the TTL if caching is enabled, or `None` for Paranoid.
52    pub fn ttl(&self) -> Option<Duration> {
53        match self {
54            SecurityLevel::Paranoid => None,
55            SecurityLevel::Standard { ttl } | SecurityLevel::Performance { ttl } => Some(*ttl),
56        }
57    }
58
59    /// Returns true if plaintext caching is enabled (Performance level).
60    pub fn caches_plaintext(&self) -> bool {
61        matches!(self, SecurityLevel::Performance { .. })
62    }
63
64    /// Returns true if data key caching is enabled (Standard or Performance).
65    pub fn caches_data_key(&self) -> bool {
66        !matches!(self, SecurityLevel::Paranoid)
67    }
68}
69
70impl Default for SecurityLevel {
71    /// Defaults to `Paranoid` for maximum security and backward compatibility.
72    fn default() -> Self {
73        SecurityLevel::Paranoid
74    }
75}