1use crate::crypto::{Crypto, EncryptionResult};
2use crate::error::{EncryptError, Result};
3use serde::{Deserialize, Serialize};
4use std::collections::HashMap;
5use std::fs;
6use std::path::PathBuf;
7use chrono::{DateTime, Utc};
8
9const VAULT_DIR: &str = ".encrypt";
10const CONFIG_FILE: &str = "vault.lock";
11const SECRETS_FILE: &str = "secrets.enc.json";
12const GITIGNORE_FILE: &str = ".gitignore";
13const LOCK_FILE: &str = "vault.unlocked";
14
15#[derive(Debug, Serialize, Deserialize)]
16pub struct VaultConfig {
17 pub password_hash: String,
18 pub salt: String,
19 pub hmac: String,
20 pub created_at: DateTime<Utc>,
21 pub version: String,
22}
23
24#[derive(Debug, Serialize, Deserialize)]
25pub struct VaultStatus {
26 pub is_locked: bool,
27 pub keys: Vec<String>,
28 pub last_modified: Option<DateTime<Utc>>,
29}
30
31#[derive(Debug, Serialize, Deserialize)]
32pub struct LockFile {
33 pub unlocked: bool,
34 pub timestamp: DateTime<Utc>,
35}
36
37pub struct Vault {
40 project_root: PathBuf,
41 vault_path: PathBuf,
42 config_path: PathBuf,
43 secrets_path: PathBuf,
44 gitignore_path: PathBuf,
45 lock_file_path: PathBuf,
46 memory_cache: HashMap<String, String>,
47}
48
49impl Vault {
50 pub fn new() -> Self {
51 let project_root = std::env::current_dir().unwrap_or_else(|_| PathBuf::from("."));
52 let vault_path = project_root.join(VAULT_DIR);
53 let config_path = vault_path.join(CONFIG_FILE);
54 let secrets_path = vault_path.join(SECRETS_FILE);
55 let gitignore_path = project_root.join(GITIGNORE_FILE);
56 let lock_file_path = vault_path.join(LOCK_FILE);
57
58 Self {
59 project_root,
60 vault_path,
61 config_path,
62 secrets_path,
63 gitignore_path,
64 lock_file_path,
65 memory_cache: HashMap::new(),
66 }
67 }
68
69 pub fn init(&self) -> Result<()> {
71 fs::create_dir_all(&self.vault_path)?;
72
73 if !self.secrets_path.exists() {
75 fs::write(&self.secrets_path, "{}")?;
76 }
77
78 if !self.config_path.exists() {
80 let initial_config = VaultConfig {
81 password_hash: String::new(),
82 salt: String::new(),
83 hmac: String::new(),
84 created_at: Utc::now(),
85 version: crate::get_version().to_string(),
86 };
87 fs::write(&self.config_path, serde_json::to_string_pretty(&initial_config)?)?;
88 }
89
90 self.update_gitignore()?;
92
93 Ok(())
94 }
95
96 fn update_gitignore(&self) -> Result<()> {
98 let gitignore_content = if self.gitignore_path.exists() {
99 fs::read_to_string(&self.gitignore_path)?
100 } else {
101 String::new()
102 };
103
104 if !gitignore_content.contains(".encrypt/") {
105 let mut file = fs::OpenOptions::new()
106 .create(true)
107 .append(true)
108 .open(&self.gitignore_path)?;
109 use std::io::Write;
110 writeln!(file, "\n# Encrypt vault\n.encrypt/")?;
111 }
112
113 Ok(())
114 }
115
116 pub fn exists(&self) -> bool {
118 self.vault_path.exists() && self.config_path.exists()
119 }
120
121 pub fn lockup(&mut self, password: &str) -> Result<()> {
123 if self.memory_cache.is_empty() {
125 self.load_secrets_from_file()?;
126 }
127
128 if self.memory_cache.is_empty() {
129 return Err(EncryptError::NoSecretsToLock);
130 }
131
132 let mut encrypted_secrets = HashMap::new();
134
135 for (key, value) in &self.memory_cache {
136 let result = Crypto::encrypt(value, password)?;
137 encrypted_secrets.insert(key.clone(), serde_json::to_string(&result)?);
138 }
139
140 let config_salt = Crypto::generate_salt();
142 let config = VaultConfig {
143 password_hash: Crypto::hash_password(password)?,
144 salt: config_salt.clone(),
145 hmac: Crypto::generate_hmac(
146 &serde_json::to_string(&encrypted_secrets)?,
147 &Crypto::derive_key(password, &config_salt)?,
148 ),
149 created_at: Utc::now(),
150 version: "1.0.0".to_string(),
151 };
152
153 fs::write(&self.secrets_path, serde_json::to_string_pretty(&encrypted_secrets)?)?;
155 fs::write(&self.config_path, serde_json::to_string_pretty(&config)?)?;
156
157 self.memory_cache.clear();
159 if self.lock_file_path.exists() {
160 fs::remove_file(&self.lock_file_path)?;
161 }
162
163 Ok(())
164 }
165
166 pub fn setup(&mut self, password: &str) -> Result<()> {
168 if !self.exists() {
169 return Err(EncryptError::VaultNotFound);
170 }
171
172 let config: VaultConfig = serde_json::from_str(&fs::read_to_string(&self.config_path)?)?;
173
174 if config.password_hash.is_empty() {
176 self.memory_cache.clear();
177 self.create_lock_file()?;
178 return Ok(());
179 }
180
181 if !Crypto::verify_password(password, &config.password_hash)? {
183 return Err(EncryptError::InvalidPassword);
184 }
185
186 let encrypted_secrets: HashMap<String, String> =
188 serde_json::from_str(&fs::read_to_string(&self.secrets_path)?)?;
189
190 self.memory_cache.clear();
191
192 for (key, encrypted_data) in encrypted_secrets {
193 if encrypted_data.starts_with('{') {
195 let result: EncryptionResult = serde_json::from_str(&encrypted_data)?;
197 let decrypted = Crypto::decrypt(&result.encrypted, &result.salt, &result.hmac, password)?;
198 self.memory_cache.insert(key, decrypted);
199 } else {
200 self.memory_cache.insert(key, encrypted_data);
202 }
203 }
204
205 self.save_secrets_to_file()?;
207 self.create_lock_file()?;
208
209 Ok(())
210 }
211
212 pub fn set(&mut self, key: &str, value: &str) -> Result<()> {
214 if !self.unlocked()? {
215 return Err(EncryptError::VaultLocked);
216 }
217
218 if self.memory_cache.is_empty() {
220 self.load_secrets_from_file()?;
221 }
222
223 self.memory_cache.insert(key.to_string(), value.to_string());
224 self.save_secrets_to_file()?;
225
226 Ok(())
227 }
228
229 pub fn get(&mut self, key: &str) -> Result<String> {
231 if !self.unlocked()? {
232 return Err(EncryptError::VaultLocked);
233 }
234
235 if self.memory_cache.is_empty() {
237 self.load_secrets_from_file()?;
238 }
239
240 self.memory_cache
241 .get(key)
242 .ok_or_else(|| EncryptError::SecretNotFound(key.to_string()))
243 .map(|s| s.clone())
244 }
245
246 pub fn all(&mut self) -> Result<HashMap<String, String>> {
248 if !self.unlocked()? {
249 return Err(EncryptError::VaultLocked);
250 }
251
252 if self.memory_cache.is_empty() {
254 self.load_secrets_from_file()?;
255 }
256
257 Ok(self.memory_cache.clone())
258 }
259
260 pub fn status(&mut self) -> Result<VaultStatus> {
262 let is_unlocked = self.unlocked()?;
264
265 if is_unlocked && self.memory_cache.is_empty() {
267 self.load_secrets_from_file()?;
268 }
269
270 let keys: Vec<String> = self.memory_cache.keys().cloned().collect();
271 let last_modified = if self.exists() {
272 Some(DateTime::from(fs::metadata(&self.config_path)?.modified()?))
273 } else {
274 None
275 };
276
277 Ok(VaultStatus {
278 is_locked: !is_unlocked,
279 keys,
280 last_modified,
281 })
282 }
283
284 pub fn reset(&self) -> Result<()> {
286 if self.vault_path.exists() {
287 fs::remove_dir_all(&self.vault_path)?;
288 }
289 Ok(())
290 }
291
292 pub fn unlocked(&self) -> Result<bool> {
294 Ok(self.lock_file_path.exists())
295 }
296
297 fn create_lock_file(&self) -> Result<()> {
299 let lock_data = LockFile {
300 unlocked: true,
301 timestamp: Utc::now(),
302 };
303 fs::write(&self.lock_file_path, serde_json::to_string_pretty(&lock_data)?)?;
304 Ok(())
305 }
306
307 fn load_secrets_from_file(&mut self) -> Result<()> {
309 if !self.secrets_path.exists() {
310 return Ok(());
311 }
312
313 let secrets: HashMap<String, String> =
314 serde_json::from_str(&fs::read_to_string(&self.secrets_path)?)?;
315
316 self.memory_cache.clear();
317 for (key, value) in secrets {
318 if value.starts_with('{') {
320 return Err(EncryptError::Crypto(format!(
324 "Secret \"{}\" is encrypted but vault is unlocked. This should not happen.",
325 key
326 )));
327 } else {
328 self.memory_cache.insert(key, value);
330 }
331 }
332
333 Ok(())
334 }
335
336 fn save_secrets_to_file(&self) -> Result<()> {
338 fs::write(&self.secrets_path, serde_json::to_string_pretty(&self.memory_cache)?)?;
339 Ok(())
340 }
341}