adk_session/encryption_key.rs
1//! AES-256-GCM encryption key management.
2//!
3//! Provides [`EncryptionKey`] for generating, loading, and managing
4//! 256-bit encryption keys used by [`EncryptedSession`](crate::EncryptedSession).
5
6use adk_core::AdkError;
7
8/// AES-256-GCM key material (256-bit / 32 bytes).
9///
10/// The internal bytes are never exposed through the `Debug` implementation
11/// to prevent accidental key leakage in logs.
12///
13/// # Example
14///
15/// ```rust,no_run
16/// use adk_session::EncryptionKey;
17///
18/// // Generate a random key
19/// let key = EncryptionKey::generate();
20///
21/// // Load from environment variable
22/// let key = EncryptionKey::from_env("MY_ENCRYPTION_KEY").unwrap();
23///
24/// // Create from raw bytes
25/// let bytes = [0u8; 32];
26/// let key = EncryptionKey::from_bytes(&bytes).unwrap();
27/// ```
28pub struct EncryptionKey {
29 bytes: [u8; 32],
30}
31
32impl std::fmt::Debug for EncryptionKey {
33 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
34 f.debug_struct("EncryptionKey").field("bytes", &"[REDACTED]").finish()
35 }
36}
37
38impl EncryptionKey {
39 /// Generate a cryptographically random 256-bit key.
40 pub fn generate() -> Self {
41 use rand::Rng;
42 let bytes: [u8; 32] = rand::rng().random();
43 Self { bytes }
44 }
45
46 /// Read a base64-encoded key from the named environment variable.
47 ///
48 /// Returns an error if the variable is not set, the value is not valid
49 /// base64, or the decoded bytes are not exactly 32 bytes.
50 pub fn from_env(var_name: &str) -> adk_core::Result<Self> {
51 let raw = std::env::var(var_name).map_err(|_| {
52 AdkError::session(format!("environment variable {var_name} is not set"))
53 })?;
54 Self::from_base64(&raw)
55 .map_err(|error| AdkError::session(format!("{var_name}: {}", error.message)))
56 }
57
58 /// Decodes a base64 key of exactly 32 bytes, as [`to_base64`](Self::to_base64) writes
59 /// and `from_env` reads.
60 ///
61 /// # Errors
62 ///
63 /// Returns an error when the text is not valid base64 or does not decode to 32 bytes.
64 pub fn from_base64(text: &str) -> adk_core::Result<Self> {
65 use base64::Engine;
66
67 let decoded = base64::engine::general_purpose::STANDARD
68 .decode(text.trim())
69 .map_err(|e| AdkError::session(format!("invalid base64 key: {e}")))?;
70 let len = decoded.len();
71 if len != 32 {
72 return Err(AdkError::session(format!("key decoded to {len} bytes, expected 32")));
73 }
74 let mut bytes = [0u8; 32];
75 bytes.copy_from_slice(&decoded);
76 Ok(Self { bytes })
77 }
78
79 /// The key as base64, the form `from_env` and [`from_base64`](Self::from_base64) read.
80 pub fn to_base64(&self) -> String {
81 use base64::Engine;
82 base64::engine::general_purpose::STANDARD.encode(self.bytes)
83 }
84
85 /// A short public identifier of the key: the first 16 hex digits of the SHA-256 of
86 /// its bytes. Safe to record in audit logs and store markers; it does not reveal the
87 /// key.
88 ///
89 /// # Example
90 ///
91 /// ```rust
92 /// use adk_session::EncryptionKey;
93 ///
94 /// let key = EncryptionKey::from_bytes(&[7; 32]).unwrap();
95 /// assert_eq!(key.id().len(), 16);
96 /// assert_eq!(key.id(), EncryptionKey::from_bytes(&[7; 32]).unwrap().id());
97 /// ```
98 pub fn id(&self) -> String {
99 use sha2::{Digest, Sha256};
100 let digest = Sha256::digest(self.bytes);
101 digest.iter().take(8).map(|byte| format!("{byte:02x}")).collect()
102 }
103
104 /// Create from a byte slice that must be exactly 32 bytes.
105 pub fn from_bytes(bytes: &[u8]) -> adk_core::Result<Self> {
106 let len = bytes.len();
107 if len != 32 {
108 return Err(AdkError::session(format!(
109 "encryption key must be exactly 32 bytes, got {len}"
110 )));
111 }
112 let mut arr = [0u8; 32];
113 arr.copy_from_slice(bytes);
114 Ok(Self { bytes: arr })
115 }
116
117 /// Return a reference to the raw key bytes.
118 pub fn as_bytes(&self) -> &[u8; 32] {
119 &self.bytes
120 }
121}