1use std::collections::HashMap;
16use std::path::Path;
17
18use crate::models::{CheckStatus, DiagnosticResult};
19use crate::modules::stack_detector::read_clean;
20
21pub const CRITICAL_VARS: &[&str] = &["API_KEY", "DATABASE_URL", "SECRET", "PORT"];
24
25pub fn parse_env(content: &str) -> HashMap<String, String> {
35 let mut out = HashMap::new();
36
37 for line in content.lines() {
38 let mut line = line.trim();
39 if line.is_empty() || line.starts_with('#') {
40 continue;
41 }
42 if let Some(rest) = line.strip_prefix("export") {
43 line = rest.trim();
44 }
45 let (key, raw_value) = match line.split_once('=') {
46 Some(pair) => pair,
47 None => continue,
48 };
49 let key = key.trim();
50 if key.is_empty() {
51 continue;
52 }
53 out.insert(key.to_string(), clean_value(raw_value));
54 }
55
56 out
57}
58
59fn clean_value(raw: &str) -> String {
61 let mut value = raw.trim();
62 if let Some(stripped) = value.strip_prefix('"').and_then(|v| v.strip_suffix('"')) {
63 value = stripped;
64 } else if let Some(stripped) = value.strip_prefix('\'').and_then(|v| v.strip_suffix('\'')) {
65 value = stripped;
66 }
67 if let Some(idx) = value.find(" #") {
68 value = value[..idx].trim_end();
69 }
70 value.to_string()
71}
72
73pub fn audit_env_files(repo_path: &str) -> DiagnosticResult {
79 let root = Path::new(repo_path);
80 let env_file = root.join(".env");
81 let example_file = root.join(".env.example");
82
83 let has_env = env_file.is_file();
84 let has_example = example_file.is_file();
85
86 match (has_env, has_example) {
87 (true, true) => audit_both(&env_file, &example_file),
88 (true, false) => audit_env_only(&env_file),
89 (false, true) => DiagnosticResult::new(
90 "Env Audit",
91 CheckStatus::Warn,
92 ".env file missing! Found .env.example template.",
93 )
94 .with_remediation("Copy .env.example to .env and fill in the values"),
95 (false, false) => DiagnosticResult::new(
96 "Env Audit",
97 CheckStatus::Pass,
98 "No .env or .env.example found; this project may not need environment variables.",
99 ),
100 }
101}
102
103fn audit_both(env_file: &Path, example_file: &Path) -> DiagnosticResult {
106 let env = read_env(env_file);
107 let example = read_env(example_file);
108
109 let mut critical_problems: Vec<&str> = Vec::new();
110 for var in CRITICAL_VARS {
111 if !example.contains_key(*var) {
112 continue;
113 }
114 match env.get(*var) {
115 None => critical_problems.push(var),
116 Some(value) if value.is_empty() => critical_problems.push(var),
117 Some(_) => {}
118 }
119 }
120
121 let mut missing_keys: Vec<&String> = example
122 .keys()
123 .filter(|key| !env.contains_key(*key))
124 .collect();
125 missing_keys.sort();
126
127 if !critical_problems.is_empty() {
128 return DiagnosticResult::new(
129 "Env Audit",
130 CheckStatus::Fail,
131 format!(
132 "Critical variables missing or empty in .env: {}",
133 critical_problems.join(", ")
134 ),
135 )
136 .with_remediation(format!(
137 "Copy and fill from .env.example: {}",
138 critical_problems.join(", ")
139 ));
140 }
141
142 if !missing_keys.is_empty() {
143 return DiagnosticResult::new(
144 "Env Audit",
145 CheckStatus::Warn,
146 format!(
147 "{} keys from .env.example are missing in .env: {}",
148 missing_keys.len(),
149 missing_keys
150 .iter()
151 .map(|k| k.as_str())
152 .collect::<Vec<_>>()
153 .join(", ")
154 ),
155 )
156 .with_remediation(format!(
157 "Add the missing keys to .env: {}",
158 missing_keys
159 .iter()
160 .map(|k| k.as_str())
161 .collect::<Vec<_>>()
162 .join(", ")
163 ));
164 }
165
166 let present = example.keys().filter(|key| env.contains_key(*key)).count();
167 DiagnosticResult::new(
168 "Env Audit",
169 CheckStatus::Pass,
170 format!(
171 "{present}/{} keys from .env.example are present in .env",
172 example.len()
173 ),
174 )
175}
176
177fn audit_env_only(env_file: &Path) -> DiagnosticResult {
179 let env = read_env(env_file);
180
181 let mut missing: Vec<&str> = Vec::new();
182 let mut empty: Vec<&str> = Vec::new();
183 for var in CRITICAL_VARS {
184 match env.get(*var) {
185 None => missing.push(var),
186 Some(value) if value.is_empty() => empty.push(var),
187 Some(_) => {}
188 }
189 }
190
191 if !missing.is_empty() {
192 return DiagnosticResult::new(
193 "Env Audit",
194 CheckStatus::Fail,
195 format!(
196 "Critical variables missing from .env: {}",
197 missing.join(", ")
198 ),
199 )
200 .with_remediation(format!("Add them to .env: {}", missing.join(", ")));
201 }
202
203 if !empty.is_empty() {
204 return DiagnosticResult::new(
205 "Env Audit",
206 CheckStatus::Fail,
207 format!("Critical variables empty in .env: {}", empty.join(", ")),
208 )
209 .with_remediation(format!("Fill in values for: {}", empty.join(", ")));
210 }
211
212 DiagnosticResult::new(
213 "Env Audit",
214 CheckStatus::Pass,
215 format!("Critical variables are set in .env ({} keys)", env.len()),
216 )
217}
218
219fn read_env(path: &Path) -> HashMap<String, String> {
221 read_clean(path)
222 .map(|content| parse_env(&content))
223 .unwrap_or_default()
224}
225
226#[doc(hidden)]
227pub fn status_label(status: CheckStatus) -> &'static str {
228 match status {
229 CheckStatus::Pass => "PASS",
230 CheckStatus::Warn => "WARN",
231 CheckStatus::Fail => "FAIL",
232 }
233}
234
235#[cfg(test)]
236mod tests {
237 use super::*;
238 use std::fs;
239 use std::path::PathBuf;
240 use std::time::{SystemTime, UNIX_EPOCH};
241
242 struct TempDir {
244 path: PathBuf,
245 }
246
247 impl TempDir {
248 fn new(label: &str) -> Self {
249 let stamp = SystemTime::now()
250 .duration_since(UNIX_EPOCH)
251 .expect("system clock")
252 .as_nanos();
253 let path = std::env::temp_dir().join(format!("limitless_env_{label}_{stamp}"));
254 fs::create_dir_all(&path).expect("create temp dir");
255 TempDir { path }
256 }
257
258 fn path(&self) -> &Path {
259 &self.path
260 }
261
262 fn write(self, relative: &str, content: &str) -> Self {
263 let full = self.path.join(relative);
264 if let Some(parent) = full.parent() {
265 fs::create_dir_all(parent).expect("create parent dirs");
266 }
267 fs::write(full, content).expect("write fixture file");
268 self
269 }
270 }
271
272 impl Drop for TempDir {
273 fn drop(&mut self) {
274 let _ = fs::remove_dir_all(&self.path);
275 }
276 }
277
278 #[test]
281 fn parse_env_skips_comments_and_blank_lines() {
282 let content = "# top comment\n\nAPI_KEY=abc\nDATABASE_URL = postgres://host/db\n\
283 # another comment\nPORT=8080 # dev default\n";
284 let env = parse_env(content);
285
286 assert_eq!(env.get("API_KEY").map(String::as_str), Some("abc"));
287 assert_eq!(
288 env.get("DATABASE_URL").map(String::as_str),
289 Some("postgres://host/db")
290 );
291 assert_eq!(env.get("PORT").map(String::as_str), Some("8080"));
292 assert_eq!(env.len(), 3);
293 }
294
295 #[test]
296 fn parse_env_strips_quotes_and_export_prefix() {
297 let content = "SECRET=\"s p a c e\"\nexport TOKEN='quoted value'\nOPEN=#c1f\n";
298 let env = parse_env(content);
299
300 assert_eq!(env.get("SECRET").map(String::as_str), Some("s p a c e"));
301 assert_eq!(env.get("TOKEN").map(String::as_str), Some("quoted value"));
302 assert_eq!(env.get("OPEN").map(String::as_str), Some("#c1f"));
303 }
304
305 #[test]
306 fn parse_env_skips_malformed_lines() {
307 let content = "JUST_A_KEY\n=orphan\nOK=1\n";
308 let env = parse_env(content);
309 assert_eq!(env.len(), 1);
310 assert_eq!(env.get("OK").map(String::as_str), Some("1"));
311 }
312
313 #[test]
316 fn example_present_env_missing_warns() {
317 let dir =
318 TempDir::new("example_only").write(".env.example", "API_KEY=change-me\nPORT=3000\n");
319
320 let result = audit_env_files(dir.path().to_str().unwrap());
321
322 assert_eq!(result.check_name, "Env Audit");
323 assert_eq!(result.status, CheckStatus::Warn);
324 assert!(result.message.contains(".env.example"));
325 assert_eq!(
326 result.remediation.as_deref(),
327 Some("Copy .env.example to .env and fill in the values")
328 );
329 }
330
331 #[test]
332 fn no_env_files_passes() {
333 let dir = TempDir::new("neither");
334 let result = audit_env_files(dir.path().to_str().unwrap());
335 assert_eq!(result.status, CheckStatus::Pass);
336 }
337
338 #[test]
339 fn critical_var_missing_from_env_fails() {
340 let dir = TempDir::new("both_missing_critical")
341 .write(
342 ".env.example",
343 "API_KEY=abc\nDATABASE_URL=postgres://db\nSECRET=s\nPORT=3000\n",
344 )
345 .write(".env", "API_KEY=abc\nPORT=3000\n");
346
347 let result = audit_env_files(dir.path().to_str().unwrap());
348
349 assert_eq!(result.status, CheckStatus::Fail);
350 assert!(result.message.contains("DATABASE_URL"));
351 assert!(result.message.contains("SECRET"));
352 assert!(result.remediation.is_some());
353 }
354
355 #[test]
356 fn critical_var_empty_in_env_fails() {
357 let dir = TempDir::new("both_empty_critical")
358 .write(".env.example", "API_KEY=abc\n")
359 .write(".env", "API_KEY=\n");
360
361 let result = audit_env_files(dir.path().to_str().unwrap());
362
363 assert_eq!(result.status, CheckStatus::Fail);
364 assert!(result.message.contains("API_KEY"));
365 }
366
367 #[test]
368 fn template_conditionals_skipped_when_not_required() {
369 let dir = TempDir::new("both_unrequired")
371 .write(".env.example", "PORT=3000\n")
372 .write(".env", "PORT=8080\n");
373
374 let result = audit_env_files(dir.path().to_str().unwrap());
375
376 assert_eq!(result.status, CheckStatus::Pass);
377 }
378
379 #[test]
380 fn missing_non_critical_key_warns() {
381 let dir = TempDir::new("both_missing_key")
382 .write(".env.example", "API_KEY=abc\nLOG_LEVEL=info\n")
383 .write(".env", "API_KEY=abc\n");
384
385 let result = audit_env_files(dir.path().to_str().unwrap());
386
387 assert_eq!(result.status, CheckStatus::Warn);
388 assert!(result.message.contains("LOG_LEVEL"));
389 }
390
391 #[test]
392 fn matching_env_passes() {
393 let dir = TempDir::new("both_match")
394 .write(
395 ".env.example",
396 "API_KEY=change-me\nDATABASE_URL=postgres://db\nPORT=3000\n",
397 )
398 .write(
399 ".env",
400 "API_KEY=real\nDATABASE_URL=postgres://prod\nPORT=8080\nEXTRA=ignored\n",
401 );
402
403 let result = audit_env_files(dir.path().to_str().unwrap());
404
405 assert_eq!(result.status, CheckStatus::Pass);
406 }
407
408 #[test]
409 fn env_only_missing_critical_fails() {
410 let dir = TempDir::new("env_only_missing").write(".env", "API_KEY=abc\n");
411
412 let result = audit_env_files(dir.path().to_str().unwrap());
413
414 assert_eq!(result.status, CheckStatus::Fail);
415 assert!(result.message.contains("DATABASE_URL"));
416 assert!(result.message.contains("SECRET"));
417 }
418
419 #[test]
420 fn env_only_complete_passes() {
421 let dir = TempDir::new("env_only_complete").write(
422 ".env",
423 "API_KEY=abc\nDATABASE_URL=pg://db\nSECRET=s\nPORT=5432\n",
424 );
425
426 let result = audit_env_files(dir.path().to_str().unwrap());
427
428 assert_eq!(result.status, CheckStatus::Pass);
429 }
430
431 #[test]
434 fn examples_of_env_audit_scenarios() {
435 let write_only =
436 TempDir::new("ex_example_only").write(".env.example", "API_KEY=change-me\nPORT=3000\n");
437 let both_ok = TempDir::new("ex_both_ok")
438 .write(".env.example", "API_KEY=x\nPORT=3000\n")
439 .write(".env", "API_KEY=real\nPORT=8080\n");
440 let both_bad = TempDir::new("ex_both_bad")
441 .write(".env.example", "API_KEY=x\nSECRET=s\n")
442 .write(".env", "API_KEY=\n");
443 let env_only = TempDir::new("ex_env_only").write(".env", "PORT=8080\n");
444 let none = TempDir::new("ex_none");
445
446 for (_, child) in [
447 ("template only", write_only.path()),
448 ("all keys present", both_ok.path()),
449 ("critical var empty", both_bad.path()),
450 ("env only, missing critical", env_only.path()),
451 ("no env files", none.path()),
452 ] {
453 let result = audit_env_files(child.to_str().unwrap());
454 eprintln!(
455 " {} Env Audit — {}",
456 status_label(result.status),
457 result.message
458 );
459 if let Some(remediation) = result.remediation {
460 eprintln!(" Fix: {remediation}");
461 }
462 }
463 }
464}