strata_storage/
keystore.rs1use std::collections::HashMap;
7use std::fs;
8use std::path::PathBuf;
9use std::sync::RwLock;
10
11use ring::aead::{
12 Aad, BoundKey, Nonce, NonceSequence, OpeningKey, SealingKey, UnboundKey, CHACHA20_POLY1305,
13 NONCE_LEN,
14};
15use ring::rand::{SecureRandom, SystemRandom};
16
17#[derive(Debug, Clone, PartialEq, Eq)]
19pub enum KeystoreError {
20 NotFound(String),
21 EncryptionError(String),
22 DecryptionError(String),
23 IoError(String),
24}
25
26impl std::fmt::Display for KeystoreError {
27 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
28 match self {
29 Self::NotFound(s) => write!(f, "Secret not found: {s}"),
30 Self::EncryptionError(s) => write!(f, "Encryption error: {s}"),
31 Self::DecryptionError(s) => write!(f, "Decryption error: {s}"),
32 Self::IoError(s) => write!(f, "I/O error: {s}"),
33 }
34 }
35}
36
37impl std::error::Error for KeystoreError {}
38
39struct SingleNonceSequence(Option<Nonce>);
40
41impl NonceSequence for SingleNonceSequence {
42 fn advance(&mut self) -> Result<Nonce, ring::error::Unspecified> {
43 self.0.take().ok_or(ring::error::Unspecified)
44 }
45}
46
47pub struct SecureKeystore;
49
50static MOCK_KEYSTORE_PATH: RwLock<Option<PathBuf>> = RwLock::new(None);
51
52impl SecureKeystore {
53 pub fn set_keystore_path(path: PathBuf) {
55 if let Ok(mut lock) = MOCK_KEYSTORE_PATH.write() {
56 *lock = Some(path);
57 }
58 }
59
60 pub fn clear_keystore_path() {
62 if let Ok(mut lock) = MOCK_KEYSTORE_PATH.write() {
63 *lock = None;
64 }
65 }
66
67 fn keystore_path() -> PathBuf {
68 if let Ok(lock) = MOCK_KEYSTORE_PATH.read() {
69 if let Some(ref p) = *lock {
70 return p.clone();
71 }
72 }
73 strata_vfs::driver::to_physical_path(&strata_vfs::app_data().join("keystore.enc"))
74 .unwrap_or_else(|_| {
75 let base = strata_vfs::resolver::resolve_root_dir(strata_vfs::VfsRoot::AppData);
76 base.join("keystore.enc")
77 })
78 }
79
80 fn key_file_path() -> PathBuf {
81 let store_path = Self::keystore_path();
82 store_path.with_extension("key")
83 }
84
85 fn get_or_create_master_key() -> Result<[u8; 32], KeystoreError> {
87 let key_path = Self::key_file_path();
88 if key_path.exists() {
89 #[cfg(unix)]
90 {
91 use std::os::unix::fs::PermissionsExt;
92 let _ = fs::set_permissions(&key_path, fs::Permissions::from_mode(0o600));
93 }
94 if let Ok(bytes) = fs::read(&key_path) {
95 if bytes.len() == 32 {
96 let mut key = [0u8; 32];
97 key.copy_from_slice(&bytes);
98 return Ok(key);
99 }
100 }
101 }
102
103 let rng = SystemRandom::new();
105 let mut key = [0u8; 32];
106 rng.fill(&mut key).map_err(|_| {
107 KeystoreError::EncryptionError("Failed to generate secure random key".into())
108 })?;
109
110 if let Some(parent) = key_path.parent() {
111 let _ = fs::create_dir_all(parent);
112 }
113
114 fs::write(&key_path, key).map_err(|e| KeystoreError::IoError(e.to_string()))?;
115
116 #[cfg(unix)]
118 {
119 use std::os::unix::fs::PermissionsExt;
120 let _ = fs::set_permissions(&key_path, fs::Permissions::from_mode(0o600));
121 }
122
123 Ok(key)
124 }
125
126 fn load_store() -> Result<HashMap<String, Vec<u8>>, KeystoreError> {
128 let path = Self::keystore_path();
129 if !path.exists() {
130 return Ok(HashMap::new());
131 }
132
133 let raw = fs::read(&path).map_err(|e| KeystoreError::IoError(e.to_string()))?;
134 if raw.len() < 16 + NONCE_LEN + 16 {
135 return Ok(HashMap::new());
136 }
137
138 if &raw[..16] != b"STRATA_KEYSTORE_" {
139 return Err(KeystoreError::DecryptionError(
140 "Invalid keystore file format magic".into(),
141 ));
142 }
143
144 let nonce_bytes = &raw[16..16 + NONCE_LEN];
145 let mut in_out = raw[16 + NONCE_LEN..].to_vec();
146
147 let master_key = Self::get_or_create_master_key()?;
148 let unbound_key = UnboundKey::new(&CHACHA20_POLY1305, &master_key)
149 .map_err(|_| KeystoreError::DecryptionError("Invalid master key".into()))?;
150
151 let nonce = Nonce::try_assume_unique_for_key(nonce_bytes)
152 .map_err(|_| KeystoreError::DecryptionError("Corrupted nonce".into()))?;
153
154 let mut opening_key = OpeningKey::new(unbound_key, SingleNonceSequence(Some(nonce)));
155 let plaintext = opening_key
156 .open_in_place(Aad::empty(), &mut in_out)
157 .map_err(|_| {
158 KeystoreError::DecryptionError(
159 "Cryptographic authentication failed: ciphertext tampered or invalid key"
160 .into(),
161 )
162 })?;
163
164 Self::deserialize_store(plaintext)
165 }
166
167 fn save_store(map: &HashMap<String, Vec<u8>>) -> Result<(), KeystoreError> {
169 let path = Self::keystore_path();
170 if let Some(parent) = path.parent() {
171 let _ = fs::create_dir_all(parent);
172 }
173
174 let serialized = Self::serialize_store(map);
175 let master_key = Self::get_or_create_master_key()?;
176
177 let rng = SystemRandom::new();
179 let mut nonce_bytes = [0u8; NONCE_LEN];
180 rng.fill(&mut nonce_bytes).map_err(|_| {
181 KeystoreError::EncryptionError("Failed to generate secure nonce".into())
182 })?;
183
184 let unbound_key = UnboundKey::new(&CHACHA20_POLY1305, &master_key)
185 .map_err(|_| KeystoreError::EncryptionError("Invalid master key length".into()))?;
186
187 let nonce = Nonce::try_assume_unique_for_key(&nonce_bytes)
188 .map_err(|_| KeystoreError::EncryptionError("Failed to initialize nonce".into()))?;
189
190 let mut sealing_key = SealingKey::new(unbound_key, SingleNonceSequence(Some(nonce)));
191 let mut ciphertext = serialized;
192 sealing_key
193 .seal_in_place_append_tag(Aad::empty(), &mut ciphertext)
194 .map_err(|_| KeystoreError::EncryptionError("AEAD encryption sealing failed".into()))?;
195
196 let mut output = Vec::with_capacity(16 + NONCE_LEN + ciphertext.len());
197 output.extend_from_slice(b"STRATA_KEYSTORE_");
198 output.extend_from_slice(&nonce_bytes);
199 output.extend_from_slice(&ciphertext);
200
201 fs::write(&path, output).map_err(|e| KeystoreError::IoError(e.to_string()))?;
202
203 #[cfg(unix)]
205 {
206 use std::os::unix::fs::PermissionsExt;
207 let _ = fs::set_permissions(&path, fs::Permissions::from_mode(0o600));
208 }
209
210 Ok(())
211 }
212
213 fn serialize_store(map: &HashMap<String, Vec<u8>>) -> Vec<u8> {
214 let mut out = Vec::new();
215 for (k, v) in map {
216 let k_bytes = k.as_bytes();
217 out.extend_from_slice(&(k_bytes.len() as u32).to_le_bytes());
218 out.extend_from_slice(k_bytes);
219 out.extend_from_slice(&(v.len() as u32).to_le_bytes());
220 out.extend_from_slice(v);
221 }
222 out
223 }
224
225 fn deserialize_store(data: &[u8]) -> Result<HashMap<String, Vec<u8>>, KeystoreError> {
226 let mut map = HashMap::new();
227 let mut cursor = 0;
228
229 while cursor + 8 <= data.len() {
230 let k_len = u32::from_le_bytes(data[cursor..cursor + 4].try_into().unwrap()) as usize;
231 cursor += 4;
232 if cursor + k_len > data.len() {
233 break;
234 }
235 let key = String::from_utf8(data[cursor..cursor + k_len].to_vec())
236 .map_err(|_| KeystoreError::DecryptionError("Invalid UTF-8 in key".into()))?;
237 cursor += k_len;
238
239 if cursor + 4 > data.len() {
240 break;
241 }
242 let v_len = u32::from_le_bytes(data[cursor..cursor + 4].try_into().unwrap()) as usize;
243 cursor += 4;
244 if cursor + v_len > data.len() {
245 break;
246 }
247 let val = data[cursor..cursor + v_len].to_vec();
248 cursor += v_len;
249
250 map.insert(key, val);
251 }
252
253 Ok(map)
254 }
255
256 pub fn set_secret(key: &str, value: &[u8]) -> Result<(), KeystoreError> {
258 let mut store = Self::load_store()?;
259 store.insert(key.to_string(), value.to_vec());
260 Self::save_store(&store)
261 }
262
263 pub fn get_secret(key: &str) -> Result<Option<Vec<u8>>, KeystoreError> {
265 let store = Self::load_store()?;
266 Ok(store.get(key).cloned())
267 }
268
269 pub fn delete_secret(key: &str) -> Result<bool, KeystoreError> {
271 let mut store = Self::load_store()?;
272 let existed = store.remove(key).is_some();
273 if existed {
274 Self::save_store(&store)?;
275 }
276 Ok(existed)
277 }
278
279 pub fn has_secret(key: &str) -> bool {
281 Self::load_store()
282 .map(|m| m.contains_key(key))
283 .unwrap_or(false)
284 }
285}